babylon.max.js 4.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. var finalVertexCode;
  157. this._loadVertexShaderAsync(vertexSource)
  158. .then(function (vertexCode) {
  159. return _this._processIncludesAsync(vertexCode);
  160. })
  161. .then(function (vertexCodeWithIncludes) {
  162. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  163. return _this._loadFragmentShaderAsync(fragmentSource);
  164. })
  165. .then(function (fragmentCode) {
  166. return _this._processIncludesAsync(fragmentCode);
  167. })
  168. .then(function (fragmentCodeWithIncludes) {
  169. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  170. if (baseName) {
  171. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  172. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  173. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  174. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  175. }
  176. else {
  177. _this._vertexSourceCode = finalVertexCode;
  178. _this._fragmentSourceCode = migratedFragmentCode;
  179. }
  180. _this._prepareEffect();
  181. });
  182. }
  183. Object.defineProperty(Effect.prototype, "key", {
  184. get: function () {
  185. return this._key;
  186. },
  187. enumerable: true,
  188. configurable: true
  189. });
  190. // Properties
  191. Effect.prototype.isReady = function () {
  192. return this._isReady;
  193. };
  194. Effect.prototype.getEngine = function () {
  195. return this._engine;
  196. };
  197. Effect.prototype.getProgram = function () {
  198. return this._program;
  199. };
  200. Effect.prototype.getAttributesNames = function () {
  201. return this._attributesNames;
  202. };
  203. Effect.prototype.getAttributeLocation = function (index) {
  204. return this._attributes[index];
  205. };
  206. Effect.prototype.getAttributeLocationByName = function (name) {
  207. var index = this._attributesNames.indexOf(name);
  208. return this._attributes[index];
  209. };
  210. Effect.prototype.getAttributesCount = function () {
  211. return this._attributes.length;
  212. };
  213. Effect.prototype.getUniformIndex = function (uniformName) {
  214. return this._uniformsNames.indexOf(uniformName);
  215. };
  216. Effect.prototype.getUniform = function (uniformName) {
  217. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  218. };
  219. Effect.prototype.getSamplers = function () {
  220. return this._samplers;
  221. };
  222. Effect.prototype.getCompilationError = function () {
  223. return this._compilationError;
  224. };
  225. // Methods
  226. Effect.prototype.executeWhenCompiled = function (func) {
  227. if (this.isReady()) {
  228. func(this);
  229. return;
  230. }
  231. this.onCompileObservable.add(function (effect) {
  232. func(effect);
  233. });
  234. };
  235. /** @ignore */
  236. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  237. if (BABYLON.Tools.IsWindowObjectExist()) {
  238. // DOM element ?
  239. if (vertex instanceof HTMLElement) {
  240. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  241. return Promise.resolve(vertexCode);
  242. }
  243. }
  244. // Base64 encoded ?
  245. if (vertex.substr(0, 7) === "base64:") {
  246. var vertexBinary = window.atob(vertex.substr(7));
  247. return Promise.resolve(vertexBinary);
  248. }
  249. // Is in local store ?
  250. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  251. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  252. }
  253. var vertexShaderUrl;
  254. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  255. vertexShaderUrl = vertex;
  256. }
  257. else {
  258. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  259. }
  260. // Vertex shader
  261. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  262. };
  263. /** @ignore */
  264. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  265. if (BABYLON.Tools.IsWindowObjectExist()) {
  266. // DOM element ?
  267. if (fragment instanceof HTMLElement) {
  268. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  269. return Promise.resolve(fragmentCode);
  270. }
  271. }
  272. // Base64 encoded ?
  273. if (fragment.substr(0, 7) === "base64:") {
  274. var fragmentBinary = window.atob(fragment.substr(7));
  275. return Promise.resolve(fragmentBinary);
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  280. }
  281. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  282. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  283. }
  284. var fragmentShaderUrl;
  285. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  286. fragmentShaderUrl = fragment;
  287. }
  288. else {
  289. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  290. }
  291. // Fragment shader
  292. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  293. };
  294. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  295. // Rebuild shaders source code
  296. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  297. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  298. vertexCode = prefix + vertexCode;
  299. fragmentCode = prefix + fragmentCode;
  300. // Number lines of shaders source code
  301. var i = 2;
  302. var regex = /\n/gm;
  303. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  304. i = 2;
  305. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. // Dump shaders name and formatted source code
  307. if (this.name.vertexElement) {
  308. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  309. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  310. }
  311. else if (this.name.vertex) {
  312. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  313. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  314. }
  315. else {
  316. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  317. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  318. }
  319. };
  320. ;
  321. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  322. var preparedSourceCode = this._processPrecision(sourceCode);
  323. if (this._engine.webGLVersion == 1) {
  324. return preparedSourceCode;
  325. }
  326. // Already converted
  327. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  328. return preparedSourceCode.replace("#version 300 es", "");
  329. }
  330. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  331. // Remove extensions
  332. // #extension GL_OES_standard_derivatives : enable
  333. // #extension GL_EXT_shader_texture_lod : enable
  334. // #extension GL_EXT_frag_depth : enable
  335. // #extension GL_EXT_draw_buffers : require
  336. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  337. var result = preparedSourceCode.replace(regex, "");
  338. // Migrate to GLSL v300
  339. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  340. result = result.replace(/attribute[ \t]/g, "in ");
  341. result = result.replace(/[ \t]attribute/g, " in");
  342. if (isFragment) {
  343. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  344. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  345. result = result.replace(/texture2D\s*\(/g, "texture(");
  346. result = result.replace(/textureCube\s*\(/g, "texture(");
  347. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  348. result = result.replace(/gl_FragColor/g, "glFragColor");
  349. result = result.replace(/gl_FragData/g, "glFragData");
  350. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  351. }
  352. return result;
  353. };
  354. Effect.prototype._processIncludesAsync = function (sourceCode) {
  355. var _this = this;
  356. return new Promise(function (resolve, reject) {
  357. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  358. var match = regex.exec(sourceCode);
  359. var returnValue = sourceCode;
  360. while (match != null) {
  361. var includeFile = match[1];
  362. // Uniform declaration
  363. if (includeFile.indexOf("__decl__") !== -1) {
  364. includeFile = includeFile.replace(/__decl__/, "");
  365. if (_this._engine.supportsUniformBuffers) {
  366. includeFile = includeFile.replace(/Vertex/, "Ubo");
  367. includeFile = includeFile.replace(/Fragment/, "Ubo");
  368. }
  369. includeFile = includeFile + "Declaration";
  370. }
  371. if (Effect.IncludesShadersStore[includeFile]) {
  372. // Substitution
  373. var includeContent = Effect.IncludesShadersStore[includeFile];
  374. if (match[2]) {
  375. var splits = match[3].split(",");
  376. for (var index = 0; index < splits.length; index += 2) {
  377. var source = new RegExp(splits[index], "g");
  378. var dest = splits[index + 1];
  379. includeContent = includeContent.replace(source, dest);
  380. }
  381. }
  382. if (match[4]) {
  383. var indexString = match[5];
  384. if (indexString.indexOf("..") !== -1) {
  385. var indexSplits = indexString.split("..");
  386. var minIndex = parseInt(indexSplits[0]);
  387. var maxIndex = parseInt(indexSplits[1]);
  388. var sourceIncludeContent = includeContent.slice(0);
  389. includeContent = "";
  390. if (isNaN(maxIndex)) {
  391. maxIndex = _this._indexParameters[indexSplits[1]];
  392. }
  393. for (var i = minIndex; i < maxIndex; i++) {
  394. if (!_this._engine.supportsUniformBuffers) {
  395. // Ubo replacement
  396. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  397. return p1 + "{X}";
  398. });
  399. }
  400. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  401. }
  402. }
  403. else {
  404. if (!_this._engine.supportsUniformBuffers) {
  405. // Ubo replacement
  406. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  407. return p1 + "{X}";
  408. });
  409. }
  410. includeContent = includeContent.replace(/\{X\}/g, indexString);
  411. }
  412. }
  413. // Replace
  414. returnValue = returnValue.replace(match[0], includeContent);
  415. }
  416. else {
  417. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  418. _this._engine._loadFileAsync(includeShaderUrl)
  419. .then(function (fileContent) {
  420. Effect.IncludesShadersStore[includeFile] = fileContent;
  421. return _this._processIncludesAsync(returnValue);
  422. })
  423. .then(function (returnValue) {
  424. resolve(returnValue);
  425. });
  426. return;
  427. }
  428. match = regex.exec(sourceCode);
  429. }
  430. resolve(returnValue);
  431. });
  432. };
  433. Effect.prototype._processPrecision = function (source) {
  434. if (source.indexOf("precision highp float") === -1) {
  435. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  436. source = "precision mediump float;\n" + source;
  437. }
  438. else {
  439. source = "precision highp float;\n" + source;
  440. }
  441. }
  442. else {
  443. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  444. source = source.replace("precision highp float", "precision mediump float");
  445. }
  446. }
  447. return source;
  448. };
  449. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  450. var _this = this;
  451. this._isReady = false;
  452. this._vertexSourceCodeOverride = vertexSourceCode;
  453. this._fragmentSourceCodeOverride = fragmentSourceCode;
  454. this.onError = function (effect, error) {
  455. if (onError) {
  456. onError(error);
  457. }
  458. };
  459. this.onCompiled = function () {
  460. var scenes = _this.getEngine().scenes;
  461. for (var i = 0; i < scenes.length; i++) {
  462. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  463. }
  464. if (onCompiled) {
  465. onCompiled(_this._program);
  466. }
  467. };
  468. this._fallbacks = null;
  469. this._prepareEffect();
  470. };
  471. Effect.prototype.getSpecificUniformLocations = function (names) {
  472. var engine = this._engine;
  473. return engine.getUniforms(this._program, names);
  474. };
  475. Effect.prototype._prepareEffect = function () {
  476. var attributesNames = this._attributesNames;
  477. var defines = this.defines;
  478. var fallbacks = this._fallbacks;
  479. this._valueCache = {};
  480. var previousProgram = this._program;
  481. try {
  482. var engine = this._engine;
  483. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  484. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  485. }
  486. else {
  487. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  488. }
  489. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  490. if (engine.supportsUniformBuffers) {
  491. for (var name in this._uniformBuffersNames) {
  492. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  493. }
  494. }
  495. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  496. this._attributes = engine.getAttributes(this._program, attributesNames);
  497. var index;
  498. for (index = 0; index < this._samplers.length; index++) {
  499. var sampler = this.getUniform(this._samplers[index]);
  500. if (sampler == null) {
  501. this._samplers.splice(index, 1);
  502. index--;
  503. }
  504. }
  505. engine.bindSamplers(this);
  506. this._compilationError = "";
  507. this._isReady = true;
  508. if (this.onCompiled) {
  509. this.onCompiled(this);
  510. }
  511. this.onCompileObservable.notifyObservers(this);
  512. this.onCompileObservable.clear();
  513. // Unbind mesh reference in fallbacks
  514. if (this._fallbacks) {
  515. this._fallbacks.unBindMesh();
  516. }
  517. if (previousProgram) {
  518. this.getEngine()._deleteProgram(previousProgram);
  519. }
  520. }
  521. catch (e) {
  522. this._compilationError = e.message;
  523. // Let's go through fallbacks then
  524. BABYLON.Tools.Error("Unable to compile effect:");
  525. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  526. return " " + uniform;
  527. }));
  528. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  529. return " " + attribute;
  530. }));
  531. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  532. BABYLON.Tools.Error("Error: " + this._compilationError);
  533. if (previousProgram) {
  534. this._program = previousProgram;
  535. this._isReady = true;
  536. if (this.onError) {
  537. this.onError(this, this._compilationError);
  538. }
  539. this.onErrorObservable.notifyObservers(this);
  540. }
  541. if (fallbacks && fallbacks.isMoreFallbacks) {
  542. BABYLON.Tools.Error("Trying next fallback.");
  543. this.defines = fallbacks.reduce(this.defines);
  544. this._prepareEffect();
  545. }
  546. else {
  547. if (this.onError) {
  548. this.onError(this, this._compilationError);
  549. }
  550. this.onErrorObservable.notifyObservers(this);
  551. this.onErrorObservable.clear();
  552. // Unbind mesh reference in fallbacks
  553. if (this._fallbacks) {
  554. this._fallbacks.unBindMesh();
  555. }
  556. }
  557. }
  558. };
  559. Object.defineProperty(Effect.prototype, "isSupported", {
  560. get: function () {
  561. return this._compilationError === "";
  562. },
  563. enumerable: true,
  564. configurable: true
  565. });
  566. Effect.prototype._bindTexture = function (channel, texture) {
  567. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  568. };
  569. Effect.prototype.setTexture = function (channel, texture) {
  570. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  571. };
  572. Effect.prototype.setTextureArray = function (channel, textures) {
  573. if (this._samplers.indexOf(channel + "Ex") === -1) {
  574. var initialPos = this._samplers.indexOf(channel);
  575. for (var index = 1; index < textures.length; index++) {
  576. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  577. }
  578. }
  579. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  580. };
  581. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  582. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  583. };
  584. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  585. var cache = this._valueCache[uniformName];
  586. var flag = matrix.updateFlag;
  587. if (cache !== undefined && cache === flag) {
  588. return false;
  589. }
  590. this._valueCache[uniformName] = flag;
  591. return true;
  592. };
  593. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  594. var cache = this._valueCache[uniformName];
  595. if (!cache) {
  596. cache = [x, y];
  597. this._valueCache[uniformName] = cache;
  598. return true;
  599. }
  600. var changed = false;
  601. if (cache[0] !== x) {
  602. cache[0] = x;
  603. changed = true;
  604. }
  605. if (cache[1] !== y) {
  606. cache[1] = y;
  607. changed = true;
  608. }
  609. return changed;
  610. };
  611. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  612. var cache = this._valueCache[uniformName];
  613. if (!cache) {
  614. cache = [x, y, z];
  615. this._valueCache[uniformName] = cache;
  616. return true;
  617. }
  618. var changed = false;
  619. if (cache[0] !== x) {
  620. cache[0] = x;
  621. changed = true;
  622. }
  623. if (cache[1] !== y) {
  624. cache[1] = y;
  625. changed = true;
  626. }
  627. if (cache[2] !== z) {
  628. cache[2] = z;
  629. changed = true;
  630. }
  631. return changed;
  632. };
  633. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  634. var cache = this._valueCache[uniformName];
  635. if (!cache) {
  636. cache = [x, y, z, w];
  637. this._valueCache[uniformName] = cache;
  638. return true;
  639. }
  640. var changed = false;
  641. if (cache[0] !== x) {
  642. cache[0] = x;
  643. changed = true;
  644. }
  645. if (cache[1] !== y) {
  646. cache[1] = y;
  647. changed = true;
  648. }
  649. if (cache[2] !== z) {
  650. cache[2] = z;
  651. changed = true;
  652. }
  653. if (cache[3] !== w) {
  654. cache[3] = w;
  655. changed = true;
  656. }
  657. return changed;
  658. };
  659. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  660. var bufferName = this._uniformBuffersNames[name];
  661. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  662. return;
  663. }
  664. Effect._baseCache[bufferName] = buffer;
  665. this._engine.bindUniformBufferBase(buffer, bufferName);
  666. };
  667. Effect.prototype.bindUniformBlock = function (blockName, index) {
  668. this._engine.bindUniformBlock(this._program, blockName, index);
  669. };
  670. Effect.prototype.setInt = function (uniformName, value) {
  671. var cache = this._valueCache[uniformName];
  672. if (cache !== undefined && cache === value)
  673. return this;
  674. this._valueCache[uniformName] = value;
  675. this._engine.setInt(this.getUniform(uniformName), value);
  676. return this;
  677. };
  678. Effect.prototype.setIntArray = function (uniformName, array) {
  679. this._valueCache[uniformName] = null;
  680. this._engine.setIntArray(this.getUniform(uniformName), array);
  681. return this;
  682. };
  683. Effect.prototype.setIntArray2 = function (uniformName, array) {
  684. this._valueCache[uniformName] = null;
  685. this._engine.setIntArray2(this.getUniform(uniformName), array);
  686. return this;
  687. };
  688. Effect.prototype.setIntArray3 = function (uniformName, array) {
  689. this._valueCache[uniformName] = null;
  690. this._engine.setIntArray3(this.getUniform(uniformName), array);
  691. return this;
  692. };
  693. Effect.prototype.setIntArray4 = function (uniformName, array) {
  694. this._valueCache[uniformName] = null;
  695. this._engine.setIntArray4(this.getUniform(uniformName), array);
  696. return this;
  697. };
  698. Effect.prototype.setFloatArray = function (uniformName, array) {
  699. this._valueCache[uniformName] = null;
  700. this._engine.setFloatArray(this.getUniform(uniformName), array);
  701. return this;
  702. };
  703. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  704. this._valueCache[uniformName] = null;
  705. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  706. return this;
  707. };
  708. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  709. this._valueCache[uniformName] = null;
  710. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  711. return this;
  712. };
  713. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  714. this._valueCache[uniformName] = null;
  715. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  716. return this;
  717. };
  718. Effect.prototype.setArray = function (uniformName, array) {
  719. this._valueCache[uniformName] = null;
  720. this._engine.setArray(this.getUniform(uniformName), array);
  721. return this;
  722. };
  723. Effect.prototype.setArray2 = function (uniformName, array) {
  724. this._valueCache[uniformName] = null;
  725. this._engine.setArray2(this.getUniform(uniformName), array);
  726. return this;
  727. };
  728. Effect.prototype.setArray3 = function (uniformName, array) {
  729. this._valueCache[uniformName] = null;
  730. this._engine.setArray3(this.getUniform(uniformName), array);
  731. return this;
  732. };
  733. Effect.prototype.setArray4 = function (uniformName, array) {
  734. this._valueCache[uniformName] = null;
  735. this._engine.setArray4(this.getUniform(uniformName), array);
  736. return this;
  737. };
  738. Effect.prototype.setMatrices = function (uniformName, matrices) {
  739. if (!matrices) {
  740. return this;
  741. }
  742. this._valueCache[uniformName] = null;
  743. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  744. return this;
  745. };
  746. Effect.prototype.setMatrix = function (uniformName, matrix) {
  747. if (this._cacheMatrix(uniformName, matrix)) {
  748. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  749. }
  750. return this;
  751. };
  752. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  753. this._valueCache[uniformName] = null;
  754. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  755. return this;
  756. };
  757. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  758. this._valueCache[uniformName] = null;
  759. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  760. return this;
  761. };
  762. Effect.prototype.setFloat = function (uniformName, value) {
  763. var cache = this._valueCache[uniformName];
  764. if (cache !== undefined && cache === value)
  765. return this;
  766. this._valueCache[uniformName] = value;
  767. this._engine.setFloat(this.getUniform(uniformName), value);
  768. return this;
  769. };
  770. Effect.prototype.setBool = function (uniformName, bool) {
  771. var cache = this._valueCache[uniformName];
  772. if (cache !== undefined && cache === bool)
  773. return this;
  774. this._valueCache[uniformName] = bool;
  775. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  776. return this;
  777. };
  778. Effect.prototype.setVector2 = function (uniformName, vector2) {
  779. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  780. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  781. }
  782. return this;
  783. };
  784. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  785. if (this._cacheFloat2(uniformName, x, y)) {
  786. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  787. }
  788. return this;
  789. };
  790. Effect.prototype.setVector3 = function (uniformName, vector3) {
  791. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  792. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  793. }
  794. return this;
  795. };
  796. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  797. if (this._cacheFloat3(uniformName, x, y, z)) {
  798. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  799. }
  800. return this;
  801. };
  802. Effect.prototype.setVector4 = function (uniformName, vector4) {
  803. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  804. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  805. }
  806. return this;
  807. };
  808. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  809. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  810. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  811. }
  812. return this;
  813. };
  814. Effect.prototype.setColor3 = function (uniformName, color3) {
  815. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  816. this._engine.setColor3(this.getUniform(uniformName), color3);
  817. }
  818. return this;
  819. };
  820. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  821. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  822. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  823. }
  824. return this;
  825. };
  826. Effect.ResetCache = function () {
  827. Effect._baseCache = {};
  828. };
  829. Effect._uniqueIdSeed = 0;
  830. Effect._baseCache = {};
  831. // Statics
  832. Effect.ShadersStore = {};
  833. Effect.IncludesShadersStore = {};
  834. return Effect;
  835. }());
  836. BABYLON.Effect = Effect;
  837. })(BABYLON || (BABYLON = {}));
  838. //# sourceMappingURL=babylon.effect.js.map
  839. //# sourceMappingURL=babylon.types.js.map
  840. var BABYLON;
  841. (function (BABYLON) {
  842. var KeyboardEventTypes = /** @class */ (function () {
  843. function KeyboardEventTypes() {
  844. }
  845. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  846. get: function () {
  847. return KeyboardEventTypes._KEYDOWN;
  848. },
  849. enumerable: true,
  850. configurable: true
  851. });
  852. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  853. get: function () {
  854. return KeyboardEventTypes._KEYUP;
  855. },
  856. enumerable: true,
  857. configurable: true
  858. });
  859. KeyboardEventTypes._KEYDOWN = 0x01;
  860. KeyboardEventTypes._KEYUP = 0x02;
  861. return KeyboardEventTypes;
  862. }());
  863. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  864. var KeyboardInfo = /** @class */ (function () {
  865. function KeyboardInfo(type, event) {
  866. this.type = type;
  867. this.event = event;
  868. }
  869. return KeyboardInfo;
  870. }());
  871. BABYLON.KeyboardInfo = KeyboardInfo;
  872. /**
  873. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  874. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  875. */
  876. var KeyboardInfoPre = /** @class */ (function (_super) {
  877. __extends(KeyboardInfoPre, _super);
  878. function KeyboardInfoPre(type, event) {
  879. var _this = _super.call(this, type, event) || this;
  880. _this.skipOnPointerObservable = false;
  881. return _this;
  882. }
  883. return KeyboardInfoPre;
  884. }(KeyboardInfo));
  885. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  886. })(BABYLON || (BABYLON = {}));
  887. //# sourceMappingURL=babylon.keyboardEvents.js.map
  888. var BABYLON;
  889. (function (BABYLON) {
  890. var PointerEventTypes = /** @class */ (function () {
  891. function PointerEventTypes() {
  892. }
  893. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  894. get: function () {
  895. return PointerEventTypes._POINTERDOWN;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  901. get: function () {
  902. return PointerEventTypes._POINTERUP;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  908. get: function () {
  909. return PointerEventTypes._POINTERMOVE;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  915. get: function () {
  916. return PointerEventTypes._POINTERWHEEL;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  922. get: function () {
  923. return PointerEventTypes._POINTERPICK;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  929. get: function () {
  930. return PointerEventTypes._POINTERTAP;
  931. },
  932. enumerable: true,
  933. configurable: true
  934. });
  935. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  936. get: function () {
  937. return PointerEventTypes._POINTERDOUBLETAP;
  938. },
  939. enumerable: true,
  940. configurable: true
  941. });
  942. PointerEventTypes._POINTERDOWN = 0x01;
  943. PointerEventTypes._POINTERUP = 0x02;
  944. PointerEventTypes._POINTERMOVE = 0x04;
  945. PointerEventTypes._POINTERWHEEL = 0x08;
  946. PointerEventTypes._POINTERPICK = 0x10;
  947. PointerEventTypes._POINTERTAP = 0x20;
  948. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  949. return PointerEventTypes;
  950. }());
  951. BABYLON.PointerEventTypes = PointerEventTypes;
  952. var PointerInfoBase = /** @class */ (function () {
  953. function PointerInfoBase(type, event) {
  954. this.type = type;
  955. this.event = event;
  956. }
  957. return PointerInfoBase;
  958. }());
  959. BABYLON.PointerInfoBase = PointerInfoBase;
  960. /**
  961. * This class is used to store pointer related info for the onPrePointerObservable event.
  962. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  963. */
  964. var PointerInfoPre = /** @class */ (function (_super) {
  965. __extends(PointerInfoPre, _super);
  966. function PointerInfoPre(type, event, localX, localY) {
  967. var _this = _super.call(this, type, event) || this;
  968. _this.skipOnPointerObservable = false;
  969. _this.localPosition = new BABYLON.Vector2(localX, localY);
  970. return _this;
  971. }
  972. return PointerInfoPre;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfoPre = PointerInfoPre;
  975. /**
  976. * This type contains all the data related to a pointer event in Babylon.js.
  977. * 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.
  978. */
  979. var PointerInfo = /** @class */ (function (_super) {
  980. __extends(PointerInfo, _super);
  981. function PointerInfo(type, event, pickInfo) {
  982. var _this = _super.call(this, type, event) || this;
  983. _this.pickInfo = pickInfo;
  984. return _this;
  985. }
  986. return PointerInfo;
  987. }(PointerInfoBase));
  988. BABYLON.PointerInfo = PointerInfo;
  989. })(BABYLON || (BABYLON = {}));
  990. //# sourceMappingURL=babylon.pointerEvents.js.map
  991. var BABYLON;
  992. (function (BABYLON) {
  993. BABYLON.ToGammaSpace = 1 / 2.2;
  994. BABYLON.ToLinearSpace = 2.2;
  995. BABYLON.Epsilon = 0.001;
  996. /**
  997. * Class used to hold a RBG color
  998. */
  999. var Color3 = /** @class */ (function () {
  1000. /**
  1001. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1002. * @param r defines the red component (between 0 and 1, default is 0)
  1003. * @param g defines the green component (between 0 and 1, default is 0)
  1004. * @param b defines the blue component (between 0 and 1, default is 0)
  1005. */
  1006. function Color3(
  1007. /**
  1008. * Defines the red component (between 0 and 1, default is 0)
  1009. */
  1010. r,
  1011. /**
  1012. * Defines the green component (between 0 and 1, default is 0)
  1013. */
  1014. g,
  1015. /**
  1016. * Defines the blue component (between 0 and 1, default is 0)
  1017. */
  1018. b) {
  1019. if (r === void 0) { r = 0; }
  1020. if (g === void 0) { g = 0; }
  1021. if (b === void 0) { b = 0; }
  1022. this.r = r;
  1023. this.g = g;
  1024. this.b = b;
  1025. }
  1026. /**
  1027. * Creates a string with the Color3 current values
  1028. * @returns the string representation of the Color3 object
  1029. */
  1030. Color3.prototype.toString = function () {
  1031. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1032. };
  1033. /**
  1034. * Returns the string "Color3"
  1035. * @returns "Color3"
  1036. */
  1037. Color3.prototype.getClassName = function () {
  1038. return "Color3";
  1039. };
  1040. /**
  1041. * Compute the Color3 hash code
  1042. * @returns an unique number that can be used to hash Color3 objects
  1043. */
  1044. Color3.prototype.getHashCode = function () {
  1045. var hash = this.r || 0;
  1046. hash = (hash * 397) ^ (this.g || 0);
  1047. hash = (hash * 397) ^ (this.b || 0);
  1048. return hash;
  1049. };
  1050. // Operators
  1051. /**
  1052. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1053. * @param array defines the array where to store the r,g,b components
  1054. * @param index defines an optional index in the target array to define where to start storing values
  1055. * @returns the current Color3 object
  1056. */
  1057. Color3.prototype.toArray = function (array, index) {
  1058. if (index === undefined) {
  1059. index = 0;
  1060. }
  1061. array[index] = this.r;
  1062. array[index + 1] = this.g;
  1063. array[index + 2] = this.b;
  1064. return this;
  1065. };
  1066. /**
  1067. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1068. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1069. * @returns a new {BABYLON.Color4} object
  1070. */
  1071. Color3.prototype.toColor4 = function (alpha) {
  1072. if (alpha === void 0) { alpha = 1; }
  1073. return new Color4(this.r, this.g, this.b, alpha);
  1074. };
  1075. /**
  1076. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1077. * @returns the new array
  1078. */
  1079. Color3.prototype.asArray = function () {
  1080. var result = new Array();
  1081. this.toArray(result, 0);
  1082. return result;
  1083. };
  1084. /**
  1085. * Returns the luminance value
  1086. * @returns a float value
  1087. */
  1088. Color3.prototype.toLuminance = function () {
  1089. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1090. };
  1091. /**
  1092. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1093. * @param otherColor defines the second operand
  1094. * @returns the new Color3 object
  1095. */
  1096. Color3.prototype.multiply = function (otherColor) {
  1097. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1098. };
  1099. /**
  1100. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1101. * @param otherColor defines the second operand
  1102. * @param result defines the Color3 object where to store the result
  1103. * @returns the current Color3
  1104. */
  1105. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1106. result.r = this.r * otherColor.r;
  1107. result.g = this.g * otherColor.g;
  1108. result.b = this.b * otherColor.b;
  1109. return this;
  1110. };
  1111. /**
  1112. * Determines equality between Color3 objects
  1113. * @param otherColor defines the second operand
  1114. * @returns true if the rgb values are equal to the passed ones
  1115. */
  1116. Color3.prototype.equals = function (otherColor) {
  1117. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1118. };
  1119. /**
  1120. * Determines equality between the current Color3 object and a set of r,b,g values
  1121. * @param r defines the red component to check
  1122. * @param g defines the green component to check
  1123. * @param b defines the blue component to check
  1124. * @returns true if the rgb values are equal to the passed ones
  1125. */
  1126. Color3.prototype.equalsFloats = function (r, g, b) {
  1127. return this.r === r && this.g === g && this.b === b;
  1128. };
  1129. /**
  1130. * Multiplies in place each rgb value by scale
  1131. * @param scale defines the scaling factor
  1132. * @returns the updated Color3.
  1133. */
  1134. Color3.prototype.scale = function (scale) {
  1135. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1136. };
  1137. /**
  1138. * Multiplies the rgb values by scale and stores the result into "result"
  1139. * @param scale defines the scaling factor
  1140. * @param result defines the Color3 object where to store the result
  1141. * @returns the unmodified current Color3.
  1142. */
  1143. Color3.prototype.scaleToRef = function (scale, result) {
  1144. result.r = this.r * scale;
  1145. result.g = this.g * scale;
  1146. result.b = this.b * scale;
  1147. return this;
  1148. };
  1149. /**
  1150. * Clamps the rgb values by the min and max values and stores the result into "result"
  1151. * @param min defines minimum clamping value (default is 0)
  1152. * @param max defines maximum clamping value (default is 1)
  1153. * @param result defines color to store the result into
  1154. * @returns the original Color3
  1155. */
  1156. Color3.prototype.clampToRef = function (min, max, result) {
  1157. if (min === void 0) { min = 0; }
  1158. if (max === void 0) { max = 1; }
  1159. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1160. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1161. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1162. return this;
  1163. };
  1164. /**
  1165. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1166. * @param otherColor defines the second operand
  1167. * @returns the new Color3
  1168. */
  1169. Color3.prototype.add = function (otherColor) {
  1170. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1171. };
  1172. /**
  1173. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1174. * @param otherColor defines the second operand
  1175. * @param result defines Color3 object to store the result into
  1176. * @returns the unmodified current Color3
  1177. */
  1178. Color3.prototype.addToRef = function (otherColor, result) {
  1179. result.r = this.r + otherColor.r;
  1180. result.g = this.g + otherColor.g;
  1181. result.b = this.b + otherColor.b;
  1182. return this;
  1183. };
  1184. /**
  1185. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1186. * @param otherColor defines the second operand
  1187. * @returns the new Color3
  1188. */
  1189. Color3.prototype.subtract = function (otherColor) {
  1190. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1191. };
  1192. /**
  1193. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1194. * @param otherColor defines the second operand
  1195. * @param result defines Color3 object to store the result into
  1196. * @returns the unmodified current Color3
  1197. */
  1198. Color3.prototype.subtractToRef = function (otherColor, result) {
  1199. result.r = this.r - otherColor.r;
  1200. result.g = this.g - otherColor.g;
  1201. result.b = this.b - otherColor.b;
  1202. return this;
  1203. };
  1204. /**
  1205. * Copy the current object
  1206. * @returns a new Color3 copied the current one
  1207. */
  1208. Color3.prototype.clone = function () {
  1209. return new Color3(this.r, this.g, this.b);
  1210. };
  1211. /**
  1212. * Copies the rgb values from the source in the current Color3
  1213. * @param source defines the source Color3 object
  1214. * @returns the updated Color3 object
  1215. */
  1216. Color3.prototype.copyFrom = function (source) {
  1217. this.r = source.r;
  1218. this.g = source.g;
  1219. this.b = source.b;
  1220. return this;
  1221. };
  1222. /**
  1223. * Updates the Color3 rgb values from the passed floats
  1224. * @param r defines the red component to read from
  1225. * @param g defines the green component to read from
  1226. * @param b defines the blue component to read from
  1227. * @returns the current Color3 object
  1228. */
  1229. Color3.prototype.copyFromFloats = function (r, g, b) {
  1230. this.r = r;
  1231. this.g = g;
  1232. this.b = b;
  1233. return this;
  1234. };
  1235. /**
  1236. * Updates the Color3 rgb values from the passed floats
  1237. * @param r defines the red component to read from
  1238. * @param g defines the green component to read from
  1239. * @param b defines the blue component to read from
  1240. * @returns the current Color3 object
  1241. */
  1242. Color3.prototype.set = function (r, g, b) {
  1243. return this.copyFromFloats(r, g, b);
  1244. };
  1245. /**
  1246. * Compute the Color3 hexadecimal code as a string
  1247. * @returns a string containing the hexadecimal representation of the Color3 object
  1248. */
  1249. Color3.prototype.toHexString = function () {
  1250. var intR = (this.r * 255) | 0;
  1251. var intG = (this.g * 255) | 0;
  1252. var intB = (this.b * 255) | 0;
  1253. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1254. };
  1255. /**
  1256. * Computes a new Color3 converted from the current one to linear space
  1257. * @returns a new Color3 object
  1258. */
  1259. Color3.prototype.toLinearSpace = function () {
  1260. var convertedColor = new Color3();
  1261. this.toLinearSpaceToRef(convertedColor);
  1262. return convertedColor;
  1263. };
  1264. /**
  1265. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1266. * @param convertedColor defines the Color3 object where to store the linear space version
  1267. * @returns the unmodified Color3
  1268. */
  1269. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1270. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1271. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1272. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1273. return this;
  1274. };
  1275. /**
  1276. * Computes a new Color3 converted from the current one to gamma space
  1277. * @returns a new Color3 object
  1278. */
  1279. Color3.prototype.toGammaSpace = function () {
  1280. var convertedColor = new Color3();
  1281. this.toGammaSpaceToRef(convertedColor);
  1282. return convertedColor;
  1283. };
  1284. /**
  1285. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1286. * @param convertedColor defines the Color3 object where to store the gamma space version
  1287. * @returns the unmodified Color3
  1288. */
  1289. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1290. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1291. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1292. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1293. return this;
  1294. };
  1295. // Statics
  1296. /**
  1297. * Creates a new Color3 from the string containing valid hexadecimal values
  1298. * @param hex defines a string containing valid hexadecimal values
  1299. * @returns a new Color3 object
  1300. */
  1301. Color3.FromHexString = function (hex) {
  1302. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1303. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1304. return new Color3(0, 0, 0);
  1305. }
  1306. var r = parseInt(hex.substring(1, 3), 16);
  1307. var g = parseInt(hex.substring(3, 5), 16);
  1308. var b = parseInt(hex.substring(5, 7), 16);
  1309. return Color3.FromInts(r, g, b);
  1310. };
  1311. /**
  1312. * Creates a new Vector3 from the starting index of the passed array
  1313. * @param array defines the source array
  1314. * @param offset defines an offset in the source array
  1315. * @returns a new Color3 object
  1316. */
  1317. Color3.FromArray = function (array, offset) {
  1318. if (offset === void 0) { offset = 0; }
  1319. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1320. };
  1321. /**
  1322. * Creates a new Color3 from integer values (< 256)
  1323. * @param r defines the red component to read from (value between 0 and 255)
  1324. * @param g defines the green component to read from (value between 0 and 255)
  1325. * @param b defines the blue component to read from (value between 0 and 255)
  1326. * @returns a new Color3 object
  1327. */
  1328. Color3.FromInts = function (r, g, b) {
  1329. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1330. };
  1331. /**
  1332. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1333. * @param start defines the start Color3 value
  1334. * @param end defines the end Color3 value
  1335. * @param amount defines the gradient value between start and end
  1336. * @returns a new Color3 object
  1337. */
  1338. Color3.Lerp = function (start, end, amount) {
  1339. var r = start.r + ((end.r - start.r) * amount);
  1340. var g = start.g + ((end.g - start.g) * amount);
  1341. var b = start.b + ((end.b - start.b) * amount);
  1342. return new Color3(r, g, b);
  1343. };
  1344. /**
  1345. * Returns a Color3 value containing a red color
  1346. * @returns a new Color3 object
  1347. */
  1348. Color3.Red = function () { return new Color3(1, 0, 0); };
  1349. /**
  1350. * Returns a Color3 value containing a green color
  1351. * @returns a new Color3 object
  1352. */
  1353. Color3.Green = function () { return new Color3(0, 1, 0); };
  1354. /**
  1355. * Returns a Color3 value containing a blue color
  1356. * @returns a new Color3 object
  1357. */
  1358. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1359. /**
  1360. * Returns a Color3 value containing a black color
  1361. * @returns a new Color3 object
  1362. */
  1363. Color3.Black = function () { return new Color3(0, 0, 0); };
  1364. /**
  1365. * Returns a Color3 value containing a white color
  1366. * @returns a new Color3 object
  1367. */
  1368. Color3.White = function () { return new Color3(1, 1, 1); };
  1369. /**
  1370. * Returns a Color3 value containing a purple color
  1371. * @returns a new Color3 object
  1372. */
  1373. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1374. /**
  1375. * Returns a Color3 value containing a magenta color
  1376. * @returns a new Color3 object
  1377. */
  1378. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1379. /**
  1380. * Returns a Color3 value containing a yellow color
  1381. * @returns a new Color3 object
  1382. */
  1383. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1384. /**
  1385. * Returns a Color3 value containing a gray color
  1386. * @returns a new Color3 object
  1387. */
  1388. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1389. /**
  1390. * Returns a Color3 value containing a teal color
  1391. * @returns a new Color3 object
  1392. */
  1393. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1394. /**
  1395. * Returns a Color3 value containing a random color
  1396. * @returns a new Color3 object
  1397. */
  1398. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1399. return Color3;
  1400. }());
  1401. BABYLON.Color3 = Color3;
  1402. /**
  1403. * Class used to hold a RBGA color
  1404. */
  1405. var Color4 = /** @class */ (function () {
  1406. /**
  1407. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1408. * @param r defines the red component (between 0 and 1, default is 0)
  1409. * @param g defines the green component (between 0 and 1, default is 0)
  1410. * @param b defines the blue component (between 0 and 1, default is 0)
  1411. * @param a defines the alpha component (between 0 and 1, default is 1)
  1412. */
  1413. function Color4(
  1414. /**
  1415. * Defines the red component (between 0 and 1, default is 0)
  1416. */
  1417. r,
  1418. /**
  1419. * Defines the green component (between 0 and 1, default is 0)
  1420. */
  1421. g,
  1422. /**
  1423. * Defines the blue component (between 0 and 1, default is 0)
  1424. */
  1425. b,
  1426. /**
  1427. * Defines the alpha component (between 0 and 1, default is 1)
  1428. */
  1429. a) {
  1430. if (r === void 0) { r = 0; }
  1431. if (g === void 0) { g = 0; }
  1432. if (b === void 0) { b = 0; }
  1433. if (a === void 0) { a = 1; }
  1434. this.r = r;
  1435. this.g = g;
  1436. this.b = b;
  1437. this.a = a;
  1438. }
  1439. // Operators
  1440. /**
  1441. * Adds in place the passed Color4 values to the current Color4 object
  1442. * @param right defines the second operand
  1443. * @returns the current updated Color4 object
  1444. */
  1445. Color4.prototype.addInPlace = function (right) {
  1446. this.r += right.r;
  1447. this.g += right.g;
  1448. this.b += right.b;
  1449. this.a += right.a;
  1450. return this;
  1451. };
  1452. /**
  1453. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1454. * @returns the new array
  1455. */
  1456. Color4.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Stores from the starting index in the passed array the Color4 successive values
  1463. * @param array defines the array where to store the r,g,b components
  1464. * @param index defines an optional index in the target array to define where to start storing values
  1465. * @returns the current Color4 object
  1466. */
  1467. Color4.prototype.toArray = function (array, index) {
  1468. if (index === undefined) {
  1469. index = 0;
  1470. }
  1471. array[index] = this.r;
  1472. array[index + 1] = this.g;
  1473. array[index + 2] = this.b;
  1474. array[index + 3] = this.a;
  1475. return this;
  1476. };
  1477. /**
  1478. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1479. * @param right defines the second operand
  1480. * @returns a new Color4 object
  1481. */
  1482. Color4.prototype.add = function (right) {
  1483. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1484. };
  1485. /**
  1486. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1487. * @param right defines the second operand
  1488. * @returns a new Color4 object
  1489. */
  1490. Color4.prototype.subtract = function (right) {
  1491. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1492. };
  1493. /**
  1494. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1495. * @param right defines the second operand
  1496. * @param result defines the Color4 object where to store the result
  1497. * @returns the current Color4 object
  1498. */
  1499. Color4.prototype.subtractToRef = function (right, result) {
  1500. result.r = this.r - right.r;
  1501. result.g = this.g - right.g;
  1502. result.b = this.b - right.b;
  1503. result.a = this.a - right.a;
  1504. return this;
  1505. };
  1506. /**
  1507. * Creates a new Color4 with the current Color4 values multiplied by scale
  1508. * @param scale defines the scaling factor to apply
  1509. * @returns a new Color4 object
  1510. */
  1511. Color4.prototype.scale = function (scale) {
  1512. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1513. };
  1514. /**
  1515. * Multiplies the current Color4 values by scale and stores the result in "result"
  1516. * @param scale defines the scaling factor to apply
  1517. * @param result defines the Color4 object where to store the result
  1518. * @returns the current Color4.
  1519. */
  1520. Color4.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. result.a = this.a * scale;
  1525. return this;
  1526. };
  1527. /**
  1528. * Clamps the rgb values by the min and max values and stores the result into "result"
  1529. * @param min defines minimum clamping value (default is 0)
  1530. * @param max defines maximum clamping value (default is 1)
  1531. * @param result defines color to store the result into.
  1532. * @returns the cuurent Color4
  1533. */
  1534. Color4.prototype.clampToRef = function (min, max, result) {
  1535. if (min === void 0) { min = 0; }
  1536. if (max === void 0) { max = 1; }
  1537. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1538. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1539. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1540. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1541. return this;
  1542. };
  1543. /**
  1544. * Multipy an Color4 value by another and return a new Color4 object
  1545. * @param color defines the Color4 value to multiply by
  1546. * @returns a new Color4 object
  1547. */
  1548. Color4.prototype.multiply = function (color) {
  1549. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1550. };
  1551. /**
  1552. * Multipy a Color4 value by another and push the result in a reference value
  1553. * @param color defines the Color4 value to multiply by
  1554. * @param result defines the Color4 to fill the result in
  1555. * @returns the result Color4
  1556. */
  1557. Color4.prototype.multiplyToRef = function (color, result) {
  1558. result.r = this.r * color.r;
  1559. result.g = this.g * color.g;
  1560. result.b = this.b * color.b;
  1561. result.a = this.a * color.a;
  1562. return result;
  1563. };
  1564. /**
  1565. * Creates a string with the Color4 current values
  1566. * @returns the string representation of the Color4 object
  1567. */
  1568. Color4.prototype.toString = function () {
  1569. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1570. };
  1571. /**
  1572. * Returns the string "Color4"
  1573. * @returns "Color4"
  1574. */
  1575. Color4.prototype.getClassName = function () {
  1576. return "Color4";
  1577. };
  1578. /**
  1579. * Compute the Color4 hash code
  1580. * @returns an unique number that can be used to hash Color4 objects
  1581. */
  1582. Color4.prototype.getHashCode = function () {
  1583. var hash = this.r || 0;
  1584. hash = (hash * 397) ^ (this.g || 0);
  1585. hash = (hash * 397) ^ (this.b || 0);
  1586. hash = (hash * 397) ^ (this.a || 0);
  1587. return hash;
  1588. };
  1589. /**
  1590. * Creates a new Color4 copied from the current one
  1591. * @returns a new Color4 object
  1592. */
  1593. Color4.prototype.clone = function () {
  1594. return new Color4(this.r, this.g, this.b, this.a);
  1595. };
  1596. /**
  1597. * Copies the passed Color4 values into the current one
  1598. * @param source defines the source Color4 object
  1599. * @returns the current updated Color4 object
  1600. */
  1601. Color4.prototype.copyFrom = function (source) {
  1602. this.r = source.r;
  1603. this.g = source.g;
  1604. this.b = source.b;
  1605. this.a = source.a;
  1606. return this;
  1607. };
  1608. /**
  1609. * Copies the passed float values into the current one
  1610. * @param r defines the red component to read from
  1611. * @param g defines the green component to read from
  1612. * @param b defines the blue component to read from
  1613. * @param a defines the alpha component to read from
  1614. * @returns the current updated Color4 object
  1615. */
  1616. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. this.a = a;
  1621. return this;
  1622. };
  1623. /**
  1624. * Copies the passed float values into the current one
  1625. * @param r defines the red component to read from
  1626. * @param g defines the green component to read from
  1627. * @param b defines the blue component to read from
  1628. * @param a defines the alpha component to read from
  1629. * @returns the current updated Color4 object
  1630. */
  1631. Color4.prototype.set = function (r, g, b, a) {
  1632. return this.copyFromFloats(r, g, b, a);
  1633. };
  1634. /**
  1635. * Compute the Color4 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color4 object
  1637. */
  1638. Color4.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. var intA = (this.a * 255) | 0;
  1643. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1644. };
  1645. /**
  1646. * Computes a new Color4 converted from the current one to linear space
  1647. * @returns a new Color4 object
  1648. */
  1649. Color4.prototype.toLinearSpace = function () {
  1650. var convertedColor = new Color4();
  1651. this.toLinearSpaceToRef(convertedColor);
  1652. return convertedColor;
  1653. };
  1654. /**
  1655. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1656. * @param convertedColor defines the Color4 object where to store the linear space version
  1657. * @returns the unmodified Color4
  1658. */
  1659. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1660. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1661. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1662. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1663. convertedColor.a = this.a;
  1664. return this;
  1665. };
  1666. /**
  1667. * Computes a new Color4 converted from the current one to gamma space
  1668. * @returns a new Color4 object
  1669. */
  1670. Color4.prototype.toGammaSpace = function () {
  1671. var convertedColor = new Color4();
  1672. this.toGammaSpaceToRef(convertedColor);
  1673. return convertedColor;
  1674. };
  1675. /**
  1676. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  1677. * @param convertedColor defines the Color4 object where to store the gamma space version
  1678. * @returns the unmodified Color4
  1679. */
  1680. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1681. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1682. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1683. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1684. convertedColor.a = this.a;
  1685. return this;
  1686. };
  1687. // Statics
  1688. /**
  1689. * Creates a new Color4 from the string containing valid hexadecimal values
  1690. * @param hex defines a string containing valid hexadecimal values
  1691. * @returns a new Color4 object
  1692. */
  1693. Color4.FromHexString = function (hex) {
  1694. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1695. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1696. return new Color4(0.0, 0.0, 0.0, 0.0);
  1697. }
  1698. var r = parseInt(hex.substring(1, 3), 16);
  1699. var g = parseInt(hex.substring(3, 5), 16);
  1700. var b = parseInt(hex.substring(5, 7), 16);
  1701. var a = parseInt(hex.substring(7, 9), 16);
  1702. return Color4.FromInts(r, g, b, a);
  1703. };
  1704. /**
  1705. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1706. * @param left defines the start value
  1707. * @param right defines the end value
  1708. * @param amount defines the gradient factor
  1709. * @returns a new Color4 object
  1710. */
  1711. Color4.Lerp = function (left, right, amount) {
  1712. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1713. Color4.LerpToRef(left, right, amount, result);
  1714. return result;
  1715. };
  1716. /**
  1717. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  1718. * @param left defines the start value
  1719. * @param right defines the end value
  1720. * @param amount defines the gradient factor
  1721. * @param result defines the Color4 object where to store data
  1722. */
  1723. Color4.LerpToRef = function (left, right, amount, result) {
  1724. result.r = left.r + (right.r - left.r) * amount;
  1725. result.g = left.g + (right.g - left.g) * amount;
  1726. result.b = left.b + (right.b - left.b) * amount;
  1727. result.a = left.a + (right.a - left.a) * amount;
  1728. };
  1729. /**
  1730. * Creates a new Color4 from the starting index element of the passed array
  1731. * @param array defines the source array to read from
  1732. * @param offset defines the offset in the source array
  1733. * @returns a new Color4 object
  1734. */
  1735. Color4.FromArray = function (array, offset) {
  1736. if (offset === void 0) { offset = 0; }
  1737. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1738. };
  1739. /**
  1740. * Creates a new Color3 from integer values (< 256)
  1741. * @param r defines the red component to read from (value between 0 and 255)
  1742. * @param g defines the green component to read from (value between 0 and 255)
  1743. * @param b defines the blue component to read from (value between 0 and 255)
  1744. * @param a defines the alpha component to read from (value between 0 and 255)
  1745. * @returns a new Color3 object
  1746. */
  1747. Color4.FromInts = function (r, g, b, a) {
  1748. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1749. };
  1750. /**
  1751. * Check the content of a given array and convert it to an array containing RGBA data
  1752. * If the original array was already containing count * 4 values then it is returned directly
  1753. * @param colors defines the array to check
  1754. * @param count defines the number of RGBA data to expect
  1755. * @returns an array containing count * 4 values (RGBA)
  1756. */
  1757. Color4.CheckColors4 = function (colors, count) {
  1758. // Check if color3 was used
  1759. if (colors.length === count * 3) {
  1760. var colors4 = [];
  1761. for (var index = 0; index < colors.length; index += 3) {
  1762. var newIndex = (index / 3) * 4;
  1763. colors4[newIndex] = colors[index];
  1764. colors4[newIndex + 1] = colors[index + 1];
  1765. colors4[newIndex + 2] = colors[index + 2];
  1766. colors4[newIndex + 3] = 1.0;
  1767. }
  1768. return colors4;
  1769. }
  1770. return colors;
  1771. };
  1772. return Color4;
  1773. }());
  1774. BABYLON.Color4 = Color4;
  1775. var Vector2 = /** @class */ (function () {
  1776. /**
  1777. * Creates a new Vector2 from the passed x and y coordinates.
  1778. */
  1779. function Vector2(x, y) {
  1780. this.x = x;
  1781. this.y = y;
  1782. }
  1783. /**
  1784. * Returns a string with the Vector2 coordinates.
  1785. */
  1786. Vector2.prototype.toString = function () {
  1787. return "{X: " + this.x + " Y:" + this.y + "}";
  1788. };
  1789. /**
  1790. * Returns the string "Vector2"
  1791. */
  1792. Vector2.prototype.getClassName = function () {
  1793. return "Vector2";
  1794. };
  1795. /**
  1796. * Returns the Vector2 hash code as a number.
  1797. */
  1798. Vector2.prototype.getHashCode = function () {
  1799. var hash = this.x || 0;
  1800. hash = (hash * 397) ^ (this.y || 0);
  1801. return hash;
  1802. };
  1803. // Operators
  1804. /**
  1805. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1806. * Returns the Vector2.
  1807. */
  1808. Vector2.prototype.toArray = function (array, index) {
  1809. if (index === void 0) { index = 0; }
  1810. array[index] = this.x;
  1811. array[index + 1] = this.y;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new array with 2 elements : the Vector2 coordinates.
  1816. */
  1817. Vector2.prototype.asArray = function () {
  1818. var result = new Array();
  1819. this.toArray(result, 0);
  1820. return result;
  1821. };
  1822. /**
  1823. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1824. * Returns the updated Vector2.
  1825. */
  1826. Vector2.prototype.copyFrom = function (source) {
  1827. this.x = source.x;
  1828. this.y = source.y;
  1829. return this;
  1830. };
  1831. /**
  1832. * Sets the Vector2 coordinates with the passed floats.
  1833. * Returns the updated Vector2.
  1834. */
  1835. Vector2.prototype.copyFromFloats = function (x, y) {
  1836. this.x = x;
  1837. this.y = y;
  1838. return this;
  1839. };
  1840. /**
  1841. * Sets the Vector2 coordinates with the passed floats.
  1842. * Returns the updated Vector2.
  1843. */
  1844. Vector2.prototype.set = function (x, y) {
  1845. return this.copyFromFloats(x, y);
  1846. };
  1847. /**
  1848. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1849. */
  1850. Vector2.prototype.add = function (otherVector) {
  1851. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1852. };
  1853. /**
  1854. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1855. * Returns the Vector2.
  1856. */
  1857. Vector2.prototype.addToRef = function (otherVector, result) {
  1858. result.x = this.x + otherVector.x;
  1859. result.y = this.y + otherVector.y;
  1860. return this;
  1861. };
  1862. /**
  1863. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1864. * Returns the updated Vector2.
  1865. */
  1866. Vector2.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. return this;
  1870. };
  1871. /**
  1872. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1873. */
  1874. Vector2.prototype.addVector3 = function (otherVector) {
  1875. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1876. };
  1877. /**
  1878. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1879. */
  1880. Vector2.prototype.subtract = function (otherVector) {
  1881. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1882. };
  1883. /**
  1884. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1885. * Returns the Vector2.
  1886. */
  1887. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1888. result.x = this.x - otherVector.x;
  1889. result.y = this.y - otherVector.y;
  1890. return this;
  1891. };
  1892. /**
  1893. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1894. * Returns the updated Vector2.
  1895. */
  1896. Vector2.prototype.subtractInPlace = function (otherVector) {
  1897. this.x -= otherVector.x;
  1898. this.y -= otherVector.y;
  1899. return this;
  1900. };
  1901. /**
  1902. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1903. * Returns the updated Vector2.
  1904. */
  1905. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1906. this.x *= otherVector.x;
  1907. this.y *= otherVector.y;
  1908. return this;
  1909. };
  1910. /**
  1911. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1912. */
  1913. Vector2.prototype.multiply = function (otherVector) {
  1914. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1915. };
  1916. /**
  1917. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1918. * Returns the Vector2.
  1919. */
  1920. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1921. result.x = this.x * otherVector.x;
  1922. result.y = this.y * otherVector.y;
  1923. return this;
  1924. };
  1925. /**
  1926. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1927. */
  1928. Vector2.prototype.multiplyByFloats = function (x, y) {
  1929. return new Vector2(this.x * x, this.y * y);
  1930. };
  1931. /**
  1932. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1933. */
  1934. Vector2.prototype.divide = function (otherVector) {
  1935. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1936. };
  1937. /**
  1938. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1939. * Returns the Vector2.
  1940. */
  1941. Vector2.prototype.divideToRef = function (otherVector, result) {
  1942. result.x = this.x / otherVector.x;
  1943. result.y = this.y / otherVector.y;
  1944. return this;
  1945. };
  1946. /**
  1947. * Divides the current Vector3 coordinates by the passed ones.
  1948. * Returns the updated Vector3.
  1949. */
  1950. Vector2.prototype.divideInPlace = function (otherVector) {
  1951. return this.divideToRef(otherVector, this);
  1952. };
  1953. /**
  1954. * Returns a new Vector2 with current Vector2 negated coordinates.
  1955. */
  1956. Vector2.prototype.negate = function () {
  1957. return new Vector2(-this.x, -this.y);
  1958. };
  1959. /**
  1960. * Multiply the Vector2 coordinates by scale.
  1961. * Returns the updated Vector2.
  1962. */
  1963. Vector2.prototype.scaleInPlace = function (scale) {
  1964. this.x *= scale;
  1965. this.y *= scale;
  1966. return this;
  1967. };
  1968. /**
  1969. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1970. */
  1971. Vector2.prototype.scale = function (scale) {
  1972. return new Vector2(this.x * scale, this.y * scale);
  1973. };
  1974. /**
  1975. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1976. */
  1977. Vector2.prototype.equals = function (otherVector) {
  1978. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1979. };
  1980. /**
  1981. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1982. */
  1983. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1984. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1985. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1986. };
  1987. // Properties
  1988. /**
  1989. * Returns the vector length (float).
  1990. */
  1991. Vector2.prototype.length = function () {
  1992. return Math.sqrt(this.x * this.x + this.y * this.y);
  1993. };
  1994. /**
  1995. * Returns the vector squared length (float);
  1996. */
  1997. Vector2.prototype.lengthSquared = function () {
  1998. return (this.x * this.x + this.y * this.y);
  1999. };
  2000. // Methods
  2001. /**
  2002. * Normalize the vector.
  2003. * Returns the updated Vector2.
  2004. */
  2005. Vector2.prototype.normalize = function () {
  2006. var len = this.length();
  2007. if (len === 0)
  2008. return this;
  2009. var num = 1.0 / len;
  2010. this.x *= num;
  2011. this.y *= num;
  2012. return this;
  2013. };
  2014. /**
  2015. * Returns a new Vector2 copied from the Vector2.
  2016. */
  2017. Vector2.prototype.clone = function () {
  2018. return new Vector2(this.x, this.y);
  2019. };
  2020. // Statics
  2021. /**
  2022. * Returns a new Vector2(0, 0)
  2023. */
  2024. Vector2.Zero = function () {
  2025. return new Vector2(0, 0);
  2026. };
  2027. /**
  2028. * Returns a new Vector2(1, 1)
  2029. */
  2030. Vector2.One = function () {
  2031. return new Vector2(1, 1);
  2032. };
  2033. /**
  2034. * Returns a new Vector2 set from the passed index element of the passed array.
  2035. */
  2036. Vector2.FromArray = function (array, offset) {
  2037. if (offset === void 0) { offset = 0; }
  2038. return new Vector2(array[offset], array[offset + 1]);
  2039. };
  2040. /**
  2041. * Sets "result" from the passed index element of the passed array.
  2042. */
  2043. Vector2.FromArrayToRef = function (array, offset, result) {
  2044. result.x = array[offset];
  2045. result.y = array[offset + 1];
  2046. };
  2047. /**
  2048. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2049. */
  2050. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2051. var squared = amount * amount;
  2052. var cubed = amount * squared;
  2053. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2054. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2055. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2056. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2057. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2058. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2059. return new Vector2(x, y);
  2060. };
  2061. /**
  2062. * 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".
  2063. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2064. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2065. */
  2066. Vector2.Clamp = function (value, min, max) {
  2067. var x = value.x;
  2068. x = (x > max.x) ? max.x : x;
  2069. x = (x < min.x) ? min.x : x;
  2070. var y = value.y;
  2071. y = (y > max.y) ? max.y : y;
  2072. y = (y < min.y) ? min.y : y;
  2073. return new Vector2(x, y);
  2074. };
  2075. /**
  2076. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2077. */
  2078. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2079. var squared = amount * amount;
  2080. var cubed = amount * squared;
  2081. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2082. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2083. var part3 = (cubed - (2.0 * squared)) + amount;
  2084. var part4 = cubed - squared;
  2085. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2086. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2087. return new Vector2(x, y);
  2088. };
  2089. /**
  2090. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2091. */
  2092. Vector2.Lerp = function (start, end, amount) {
  2093. var x = start.x + ((end.x - start.x) * amount);
  2094. var y = start.y + ((end.y - start.y) * amount);
  2095. return new Vector2(x, y);
  2096. };
  2097. /**
  2098. * Returns the dot product (float) of the vector "left" and the vector "right".
  2099. */
  2100. Vector2.Dot = function (left, right) {
  2101. return left.x * right.x + left.y * right.y;
  2102. };
  2103. /**
  2104. * Returns a new Vector2 equal to the normalized passed vector.
  2105. */
  2106. Vector2.Normalize = function (vector) {
  2107. var newVector = vector.clone();
  2108. newVector.normalize();
  2109. return newVector;
  2110. };
  2111. /**
  2112. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2113. */
  2114. Vector2.Minimize = function (left, right) {
  2115. var x = (left.x < right.x) ? left.x : right.x;
  2116. var y = (left.y < right.y) ? left.y : right.y;
  2117. return new Vector2(x, y);
  2118. };
  2119. /**
  2120. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2121. */
  2122. Vector2.Maximize = function (left, right) {
  2123. var x = (left.x > right.x) ? left.x : right.x;
  2124. var y = (left.y > right.y) ? left.y : right.y;
  2125. return new Vector2(x, y);
  2126. };
  2127. /**
  2128. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2129. */
  2130. Vector2.Transform = function (vector, transformation) {
  2131. var r = Vector2.Zero();
  2132. Vector2.TransformToRef(vector, transformation, r);
  2133. return r;
  2134. };
  2135. /**
  2136. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2137. */
  2138. Vector2.TransformToRef = function (vector, transformation, result) {
  2139. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2140. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2141. result.x = x;
  2142. result.y = y;
  2143. };
  2144. /**
  2145. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2146. */
  2147. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2148. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2149. var sign = a < 0 ? -1 : 1;
  2150. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2151. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2152. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2153. };
  2154. /**
  2155. * Returns the distance (float) between the vectors "value1" and "value2".
  2156. */
  2157. Vector2.Distance = function (value1, value2) {
  2158. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2159. };
  2160. /**
  2161. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2162. */
  2163. Vector2.DistanceSquared = function (value1, value2) {
  2164. var x = value1.x - value2.x;
  2165. var y = value1.y - value2.y;
  2166. return (x * x) + (y * y);
  2167. };
  2168. /**
  2169. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2170. */
  2171. Vector2.Center = function (value1, value2) {
  2172. var center = value1.add(value2);
  2173. center.scaleInPlace(0.5);
  2174. return center;
  2175. };
  2176. /**
  2177. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2178. */
  2179. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2180. var l2 = Vector2.DistanceSquared(segA, segB);
  2181. if (l2 === 0.0) {
  2182. return Vector2.Distance(p, segA);
  2183. }
  2184. var v = segB.subtract(segA);
  2185. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2186. var proj = segA.add(v.multiplyByFloats(t, t));
  2187. return Vector2.Distance(p, proj);
  2188. };
  2189. return Vector2;
  2190. }());
  2191. BABYLON.Vector2 = Vector2;
  2192. var Vector3 = /** @class */ (function () {
  2193. /**
  2194. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2195. * A Vector3 is the main object used in 3D geometry.
  2196. * It can represent etiher the coordinates of a point the space, either a direction.
  2197. */
  2198. function Vector3(x, y, z) {
  2199. this.x = x;
  2200. this.y = y;
  2201. this.z = z;
  2202. }
  2203. /**
  2204. * Returns a string with the Vector3 coordinates.
  2205. */
  2206. Vector3.prototype.toString = function () {
  2207. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2208. };
  2209. /**
  2210. * Returns the string "Vector3"
  2211. */
  2212. Vector3.prototype.getClassName = function () {
  2213. return "Vector3";
  2214. };
  2215. /**
  2216. * Returns the Vector hash code.
  2217. */
  2218. Vector3.prototype.getHashCode = function () {
  2219. var hash = this.x || 0;
  2220. hash = (hash * 397) ^ (this.y || 0);
  2221. hash = (hash * 397) ^ (this.z || 0);
  2222. return hash;
  2223. };
  2224. // Operators
  2225. /**
  2226. * Returns a new array with three elements : the coordinates the Vector3.
  2227. */
  2228. Vector3.prototype.asArray = function () {
  2229. var result = [];
  2230. this.toArray(result, 0);
  2231. return result;
  2232. };
  2233. /**
  2234. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2235. * Returns the Vector3.
  2236. */
  2237. Vector3.prototype.toArray = function (array, index) {
  2238. if (index === void 0) { index = 0; }
  2239. array[index] = this.x;
  2240. array[index + 1] = this.y;
  2241. array[index + 2] = this.z;
  2242. return this;
  2243. };
  2244. /**
  2245. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2246. */
  2247. Vector3.prototype.toQuaternion = function () {
  2248. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2249. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2250. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2251. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2252. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2253. var cosy = Math.cos(this.y * 0.5);
  2254. var siny = Math.sin(this.y * 0.5);
  2255. result.x = coszMinusx * siny;
  2256. result.y = -sinzMinusx * siny;
  2257. result.z = sinxPlusz * cosy;
  2258. result.w = cosxPlusz * cosy;
  2259. return result;
  2260. };
  2261. /**
  2262. * Adds the passed vector to the current Vector3.
  2263. * Returns the updated Vector3.
  2264. */
  2265. Vector3.prototype.addInPlace = function (otherVector) {
  2266. this.x += otherVector.x;
  2267. this.y += otherVector.y;
  2268. this.z += otherVector.z;
  2269. return this;
  2270. };
  2271. /**
  2272. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2273. */
  2274. Vector3.prototype.add = function (otherVector) {
  2275. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2276. };
  2277. /**
  2278. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2279. * Returns the current Vector3.
  2280. */
  2281. Vector3.prototype.addToRef = function (otherVector, result) {
  2282. result.x = this.x + otherVector.x;
  2283. result.y = this.y + otherVector.y;
  2284. result.z = this.z + otherVector.z;
  2285. return this;
  2286. };
  2287. /**
  2288. * Subtract the passed vector from the current Vector3.
  2289. * Returns the updated Vector3.
  2290. */
  2291. Vector3.prototype.subtractInPlace = function (otherVector) {
  2292. this.x -= otherVector.x;
  2293. this.y -= otherVector.y;
  2294. this.z -= otherVector.z;
  2295. return this;
  2296. };
  2297. /**
  2298. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2299. */
  2300. Vector3.prototype.subtract = function (otherVector) {
  2301. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2302. };
  2303. /**
  2304. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2305. * Returns the current Vector3.
  2306. */
  2307. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2308. result.x = this.x - otherVector.x;
  2309. result.y = this.y - otherVector.y;
  2310. result.z = this.z - otherVector.z;
  2311. return this;
  2312. };
  2313. /**
  2314. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2315. */
  2316. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2317. return new Vector3(this.x - x, this.y - y, this.z - z);
  2318. };
  2319. /**
  2320. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2321. * Returns the current Vector3.
  2322. */
  2323. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2324. result.x = this.x - x;
  2325. result.y = this.y - y;
  2326. result.z = this.z - z;
  2327. return this;
  2328. };
  2329. /**
  2330. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2331. */
  2332. Vector3.prototype.negate = function () {
  2333. return new Vector3(-this.x, -this.y, -this.z);
  2334. };
  2335. /**
  2336. * Multiplies the Vector3 coordinates by the float "scale".
  2337. * Returns the updated Vector3.
  2338. */
  2339. Vector3.prototype.scaleInPlace = function (scale) {
  2340. this.x *= scale;
  2341. this.y *= scale;
  2342. this.z *= scale;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2347. */
  2348. Vector3.prototype.scale = function (scale) {
  2349. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2350. };
  2351. /**
  2352. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2353. * Returns the current Vector3.
  2354. */
  2355. Vector3.prototype.scaleToRef = function (scale, result) {
  2356. result.x = this.x * scale;
  2357. result.y = this.y * scale;
  2358. result.z = this.z * scale;
  2359. return this;
  2360. };
  2361. /**
  2362. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2363. */
  2364. Vector3.prototype.equals = function (otherVector) {
  2365. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2366. };
  2367. /**
  2368. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2369. */
  2370. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2371. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2372. 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);
  2373. };
  2374. /**
  2375. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2376. */
  2377. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2378. return this.x === x && this.y === y && this.z === z;
  2379. };
  2380. /**
  2381. * Muliplies the current Vector3 coordinates by the passed ones.
  2382. * Returns the updated Vector3.
  2383. */
  2384. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2385. this.x *= otherVector.x;
  2386. this.y *= otherVector.y;
  2387. this.z *= otherVector.z;
  2388. return this;
  2389. };
  2390. /**
  2391. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2392. */
  2393. Vector3.prototype.multiply = function (otherVector) {
  2394. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2395. };
  2396. /**
  2397. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2398. * Returns the current Vector3.
  2399. */
  2400. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2401. result.x = this.x * otherVector.x;
  2402. result.y = this.y * otherVector.y;
  2403. result.z = this.z * otherVector.z;
  2404. return this;
  2405. };
  2406. /**
  2407. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2408. */
  2409. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2410. return new Vector3(this.x * x, this.y * y, this.z * z);
  2411. };
  2412. /**
  2413. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2414. */
  2415. Vector3.prototype.divide = function (otherVector) {
  2416. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2417. };
  2418. /**
  2419. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2420. * Returns the current Vector3.
  2421. */
  2422. Vector3.prototype.divideToRef = function (otherVector, result) {
  2423. result.x = this.x / otherVector.x;
  2424. result.y = this.y / otherVector.y;
  2425. result.z = this.z / otherVector.z;
  2426. return this;
  2427. };
  2428. /**
  2429. * Divides the current Vector3 coordinates by the passed ones.
  2430. * Returns the updated Vector3.
  2431. */
  2432. Vector3.prototype.divideInPlace = function (otherVector) {
  2433. return this.divideToRef(otherVector, this);
  2434. };
  2435. /**
  2436. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2437. * Returns the updated Vector3.
  2438. */
  2439. Vector3.prototype.MinimizeInPlace = function (other) {
  2440. if (other.x < this.x)
  2441. this.x = other.x;
  2442. if (other.y < this.y)
  2443. this.y = other.y;
  2444. if (other.z < this.z)
  2445. this.z = other.z;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2450. * Returns the updated Vector3.
  2451. */
  2452. Vector3.prototype.MaximizeInPlace = function (other) {
  2453. if (other.x > this.x)
  2454. this.x = other.x;
  2455. if (other.y > this.y)
  2456. this.y = other.y;
  2457. if (other.z > this.z)
  2458. this.z = other.z;
  2459. return this;
  2460. };
  2461. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2462. /**
  2463. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2464. */
  2465. get: function () {
  2466. var absX = Math.abs(this.x);
  2467. var absY = Math.abs(this.y);
  2468. if (absX !== absY) {
  2469. return true;
  2470. }
  2471. var absZ = Math.abs(this.z);
  2472. if (absX !== absZ) {
  2473. return true;
  2474. }
  2475. if (absY !== absZ) {
  2476. return true;
  2477. }
  2478. return false;
  2479. },
  2480. enumerable: true,
  2481. configurable: true
  2482. });
  2483. // Properties
  2484. /**
  2485. * Returns the length of the Vector3 (float).
  2486. */
  2487. Vector3.prototype.length = function () {
  2488. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2489. };
  2490. /**
  2491. * Returns the squared length of the Vector3 (float).
  2492. */
  2493. Vector3.prototype.lengthSquared = function () {
  2494. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2495. };
  2496. /**
  2497. * Normalize the current Vector3.
  2498. * Returns the updated Vector3.
  2499. * /!\ In place operation.
  2500. */
  2501. Vector3.prototype.normalize = function () {
  2502. var len = this.length();
  2503. if (len === 0 || len === 1.0)
  2504. return this;
  2505. var num = 1.0 / len;
  2506. this.x *= num;
  2507. this.y *= num;
  2508. this.z *= num;
  2509. return this;
  2510. };
  2511. /**
  2512. * Normalize the current Vector3 to a new vector.
  2513. * @returns the new Vector3.
  2514. */
  2515. Vector3.prototype.normalizeToNew = function () {
  2516. var normalized = new Vector3(0, 0, 0);
  2517. this.normalizeToRef(normalized);
  2518. return normalized;
  2519. };
  2520. /**
  2521. * Normalize the current Vector3 to the reference.
  2522. * @param the reference to update.
  2523. * @returns the updated Vector3.
  2524. */
  2525. Vector3.prototype.normalizeToRef = function (reference) {
  2526. var len = this.length();
  2527. if (len === 0 || len === 1.0) {
  2528. reference.set(this.x, this.y, this.z);
  2529. return reference;
  2530. }
  2531. var scale = 1.0 / len;
  2532. this.scaleToRef(scale, reference);
  2533. return reference;
  2534. };
  2535. /**
  2536. * Returns a new Vector3 copied from the current Vector3.
  2537. */
  2538. Vector3.prototype.clone = function () {
  2539. return new Vector3(this.x, this.y, this.z);
  2540. };
  2541. /**
  2542. * Copies the passed vector coordinates to the current Vector3 ones.
  2543. * Returns the updated Vector3.
  2544. */
  2545. Vector3.prototype.copyFrom = function (source) {
  2546. this.x = source.x;
  2547. this.y = source.y;
  2548. this.z = source.z;
  2549. return this;
  2550. };
  2551. /**
  2552. * Copies the passed floats to the current Vector3 coordinates.
  2553. * Returns the updated Vector3.
  2554. */
  2555. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2556. this.x = x;
  2557. this.y = y;
  2558. this.z = z;
  2559. return this;
  2560. };
  2561. /**
  2562. * Copies the passed floats to the current Vector3 coordinates.
  2563. * Returns the updated Vector3.
  2564. */
  2565. Vector3.prototype.set = function (x, y, z) {
  2566. return this.copyFromFloats(x, y, z);
  2567. };
  2568. // Statics
  2569. /**
  2570. *
  2571. */
  2572. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2573. var d0 = Vector3.Dot(vector0, axis) - size;
  2574. var d1 = Vector3.Dot(vector1, axis) - size;
  2575. var s = d0 / (d0 - d1);
  2576. return s;
  2577. };
  2578. /**
  2579. * Get angle between two vectors.
  2580. * @param vector0 angle between vector0 and vector1
  2581. * @param vector1 angle between vector0 and vector1
  2582. * @param normal direction of the normal.
  2583. * @return the angle between vector0 and vector1.
  2584. */
  2585. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2586. var v0 = vector0.clone().normalize();
  2587. var v1 = vector1.clone().normalize();
  2588. var dot = Vector3.Dot(v0, v1);
  2589. var n = Vector3.Cross(v0, v1);
  2590. if (Vector3.Dot(n, normal) > 0) {
  2591. return Math.acos(dot);
  2592. }
  2593. return -Math.acos(dot);
  2594. };
  2595. /**
  2596. * Returns a new Vector3 set from the index "offset" of the passed array.
  2597. */
  2598. Vector3.FromArray = function (array, offset) {
  2599. if (!offset) {
  2600. offset = 0;
  2601. }
  2602. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2603. };
  2604. /**
  2605. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2606. * This function is deprecated. Use FromArray instead.
  2607. */
  2608. Vector3.FromFloatArray = function (array, offset) {
  2609. return Vector3.FromArray(array, offset);
  2610. };
  2611. /**
  2612. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2613. */
  2614. Vector3.FromArrayToRef = function (array, offset, result) {
  2615. result.x = array[offset];
  2616. result.y = array[offset + 1];
  2617. result.z = array[offset + 2];
  2618. };
  2619. /**
  2620. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2621. * This function is deprecated. Use FromArrayToRef instead.
  2622. */
  2623. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2624. return Vector3.FromArrayToRef(array, offset, result);
  2625. };
  2626. /**
  2627. * Sets the passed vector "result" with the passed floats.
  2628. */
  2629. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2630. result.x = x;
  2631. result.y = y;
  2632. result.z = z;
  2633. };
  2634. /**
  2635. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2636. */
  2637. Vector3.Zero = function () {
  2638. return new Vector3(0.0, 0.0, 0.0);
  2639. };
  2640. /**
  2641. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2642. */
  2643. Vector3.One = function () {
  2644. return new Vector3(1.0, 1.0, 1.0);
  2645. };
  2646. /**
  2647. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2648. */
  2649. Vector3.Up = function () {
  2650. return new Vector3(0.0, 1.0, 0.0);
  2651. };
  2652. /**
  2653. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2654. */
  2655. Vector3.Forward = function () {
  2656. return new Vector3(0.0, 0.0, 1.0);
  2657. };
  2658. /**
  2659. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2660. */
  2661. Vector3.Right = function () {
  2662. return new Vector3(1.0, 0.0, 0.0);
  2663. };
  2664. /**
  2665. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2666. */
  2667. Vector3.Left = function () {
  2668. return new Vector3(-1.0, 0.0, 0.0);
  2669. };
  2670. /**
  2671. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2672. * This method computes tranformed coordinates only, not transformed direction vectors.
  2673. */
  2674. Vector3.TransformCoordinates = function (vector, transformation) {
  2675. var result = Vector3.Zero();
  2676. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2677. return result;
  2678. };
  2679. /**
  2680. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2681. * This method computes tranformed coordinates only, not transformed direction vectors.
  2682. */
  2683. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2684. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2685. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2686. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2687. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2688. result.x = x / w;
  2689. result.y = y / w;
  2690. result.z = z / w;
  2691. };
  2692. /**
  2693. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2694. * This method computes tranformed coordinates only, not transformed direction vectors.
  2695. */
  2696. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2697. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2698. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2699. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2700. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2701. result.x = rx / rw;
  2702. result.y = ry / rw;
  2703. result.z = rz / rw;
  2704. };
  2705. /**
  2706. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2707. * This methods computes transformed normalized direction vectors only.
  2708. */
  2709. Vector3.TransformNormal = function (vector, transformation) {
  2710. var result = Vector3.Zero();
  2711. Vector3.TransformNormalToRef(vector, transformation, result);
  2712. return result;
  2713. };
  2714. /**
  2715. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2716. * This methods computes transformed normalized direction vectors only.
  2717. */
  2718. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2719. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2720. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2721. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2722. result.x = x;
  2723. result.y = y;
  2724. result.z = z;
  2725. };
  2726. /**
  2727. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2728. * This methods computes transformed normalized direction vectors only.
  2729. */
  2730. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2731. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2732. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2733. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2734. };
  2735. /**
  2736. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2737. */
  2738. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2739. var squared = amount * amount;
  2740. var cubed = amount * squared;
  2741. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2742. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2743. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2744. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2745. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2746. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2747. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2748. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2749. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2750. return new Vector3(x, y, z);
  2751. };
  2752. /**
  2753. * 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".
  2754. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2755. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2756. */
  2757. Vector3.Clamp = function (value, min, max) {
  2758. var x = value.x;
  2759. x = (x > max.x) ? max.x : x;
  2760. x = (x < min.x) ? min.x : x;
  2761. var y = value.y;
  2762. y = (y > max.y) ? max.y : y;
  2763. y = (y < min.y) ? min.y : y;
  2764. var z = value.z;
  2765. z = (z > max.z) ? max.z : z;
  2766. z = (z < min.z) ? min.z : z;
  2767. return new Vector3(x, y, z);
  2768. };
  2769. /**
  2770. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2771. */
  2772. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2773. var squared = amount * amount;
  2774. var cubed = amount * squared;
  2775. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2776. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2777. var part3 = (cubed - (2.0 * squared)) + amount;
  2778. var part4 = cubed - squared;
  2779. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2780. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2781. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2782. return new Vector3(x, y, z);
  2783. };
  2784. /**
  2785. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2786. */
  2787. Vector3.Lerp = function (start, end, amount) {
  2788. var result = new Vector3(0, 0, 0);
  2789. Vector3.LerpToRef(start, end, amount, result);
  2790. return result;
  2791. };
  2792. /**
  2793. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2794. */
  2795. Vector3.LerpToRef = function (start, end, amount, result) {
  2796. result.x = start.x + ((end.x - start.x) * amount);
  2797. result.y = start.y + ((end.y - start.y) * amount);
  2798. result.z = start.z + ((end.z - start.z) * amount);
  2799. };
  2800. /**
  2801. * Returns the dot product (float) between the vectors "left" and "right".
  2802. */
  2803. Vector3.Dot = function (left, right) {
  2804. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2805. };
  2806. /**
  2807. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2808. * The cross product is then orthogonal to both "left" and "right".
  2809. */
  2810. Vector3.Cross = function (left, right) {
  2811. var result = Vector3.Zero();
  2812. Vector3.CrossToRef(left, right, result);
  2813. return result;
  2814. };
  2815. /**
  2816. * Sets the passed vector "result" with the cross product of "left" and "right".
  2817. * The cross product is then orthogonal to both "left" and "right".
  2818. */
  2819. Vector3.CrossToRef = function (left, right, result) {
  2820. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2821. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2822. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2823. result.copyFrom(MathTmp.Vector3[0]);
  2824. };
  2825. /**
  2826. * Returns a new Vector3 as the normalization of the passed vector.
  2827. */
  2828. Vector3.Normalize = function (vector) {
  2829. var result = Vector3.Zero();
  2830. Vector3.NormalizeToRef(vector, result);
  2831. return result;
  2832. };
  2833. /**
  2834. * Sets the passed vector "result" with the normalization of the passed first vector.
  2835. */
  2836. Vector3.NormalizeToRef = function (vector, result) {
  2837. result.copyFrom(vector);
  2838. result.normalize();
  2839. };
  2840. Vector3.Project = function (vector, world, transform, viewport) {
  2841. var cw = viewport.width;
  2842. var ch = viewport.height;
  2843. var cx = viewport.x;
  2844. var cy = viewport.y;
  2845. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2846. 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);
  2847. var matrix = MathTmp.Matrix[0];
  2848. world.multiplyToRef(transform, matrix);
  2849. matrix.multiplyToRef(viewportMatrix, matrix);
  2850. return Vector3.TransformCoordinates(vector, matrix);
  2851. };
  2852. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2853. var matrix = MathTmp.Matrix[0];
  2854. world.multiplyToRef(transform, matrix);
  2855. matrix.invert();
  2856. source.x = source.x / viewportWidth * 2 - 1;
  2857. source.y = -(source.y / viewportHeight * 2 - 1);
  2858. var vector = Vector3.TransformCoordinates(source, matrix);
  2859. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2860. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2861. vector = vector.scale(1.0 / num);
  2862. }
  2863. return vector;
  2864. };
  2865. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2866. var result = Vector3.Zero();
  2867. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2868. return result;
  2869. };
  2870. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2871. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2872. };
  2873. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2874. var matrix = MathTmp.Matrix[0];
  2875. world.multiplyToRef(view, matrix);
  2876. matrix.multiplyToRef(projection, matrix);
  2877. matrix.invert();
  2878. var screenSource = MathTmp.Vector3[0];
  2879. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2880. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2881. screenSource.z = 2 * sourceZ - 1.0;
  2882. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2883. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2884. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2885. result.scaleInPlace(1.0 / num);
  2886. }
  2887. };
  2888. Vector3.Minimize = function (left, right) {
  2889. var min = left.clone();
  2890. min.MinimizeInPlace(right);
  2891. return min;
  2892. };
  2893. Vector3.Maximize = function (left, right) {
  2894. var max = left.clone();
  2895. max.MaximizeInPlace(right);
  2896. return max;
  2897. };
  2898. /**
  2899. * Returns the distance (float) between the vectors "value1" and "value2".
  2900. */
  2901. Vector3.Distance = function (value1, value2) {
  2902. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2903. };
  2904. /**
  2905. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2906. */
  2907. Vector3.DistanceSquared = function (value1, value2) {
  2908. var x = value1.x - value2.x;
  2909. var y = value1.y - value2.y;
  2910. var z = value1.z - value2.z;
  2911. return (x * x) + (y * y) + (z * z);
  2912. };
  2913. /**
  2914. * Returns a new Vector3 located at the center between "value1" and "value2".
  2915. */
  2916. Vector3.Center = function (value1, value2) {
  2917. var center = value1.add(value2);
  2918. center.scaleInPlace(0.5);
  2919. return center;
  2920. };
  2921. /**
  2922. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2923. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2924. * to something in order to rotate it from its local system to the given target system.
  2925. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2926. * Returns a new Vector3.
  2927. */
  2928. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2929. var rotation = Vector3.Zero();
  2930. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2931. return rotation;
  2932. };
  2933. /**
  2934. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2935. */
  2936. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2937. var quat = MathTmp.Quaternion[0];
  2938. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2939. quat.toEulerAnglesToRef(ref);
  2940. };
  2941. return Vector3;
  2942. }());
  2943. BABYLON.Vector3 = Vector3;
  2944. //Vector4 class created for EulerAngle class conversion to Quaternion
  2945. var Vector4 = /** @class */ (function () {
  2946. /**
  2947. * Creates a Vector4 object from the passed floats.
  2948. */
  2949. function Vector4(x, y, z, w) {
  2950. this.x = x;
  2951. this.y = y;
  2952. this.z = z;
  2953. this.w = w;
  2954. }
  2955. /**
  2956. * Returns the string with the Vector4 coordinates.
  2957. */
  2958. Vector4.prototype.toString = function () {
  2959. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2960. };
  2961. /**
  2962. * Returns the string "Vector4".
  2963. */
  2964. Vector4.prototype.getClassName = function () {
  2965. return "Vector4";
  2966. };
  2967. /**
  2968. * Returns the Vector4 hash code.
  2969. */
  2970. Vector4.prototype.getHashCode = function () {
  2971. var hash = this.x || 0;
  2972. hash = (hash * 397) ^ (this.y || 0);
  2973. hash = (hash * 397) ^ (this.z || 0);
  2974. hash = (hash * 397) ^ (this.w || 0);
  2975. return hash;
  2976. };
  2977. // Operators
  2978. /**
  2979. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2980. */
  2981. Vector4.prototype.asArray = function () {
  2982. var result = new Array();
  2983. this.toArray(result, 0);
  2984. return result;
  2985. };
  2986. /**
  2987. * Populates the passed array from the passed index with the Vector4 coordinates.
  2988. * Returns the Vector4.
  2989. */
  2990. Vector4.prototype.toArray = function (array, index) {
  2991. if (index === undefined) {
  2992. index = 0;
  2993. }
  2994. array[index] = this.x;
  2995. array[index + 1] = this.y;
  2996. array[index + 2] = this.z;
  2997. array[index + 3] = this.w;
  2998. return this;
  2999. };
  3000. /**
  3001. * Adds the passed vector to the current Vector4.
  3002. * Returns the updated Vector4.
  3003. */
  3004. Vector4.prototype.addInPlace = function (otherVector) {
  3005. this.x += otherVector.x;
  3006. this.y += otherVector.y;
  3007. this.z += otherVector.z;
  3008. this.w += otherVector.w;
  3009. return this;
  3010. };
  3011. /**
  3012. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3013. */
  3014. Vector4.prototype.add = function (otherVector) {
  3015. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3016. };
  3017. /**
  3018. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3019. * Returns the current Vector4.
  3020. */
  3021. Vector4.prototype.addToRef = function (otherVector, result) {
  3022. result.x = this.x + otherVector.x;
  3023. result.y = this.y + otherVector.y;
  3024. result.z = this.z + otherVector.z;
  3025. result.w = this.w + otherVector.w;
  3026. return this;
  3027. };
  3028. /**
  3029. * Subtract in place the passed vector from the current Vector4.
  3030. * Returns the updated Vector4.
  3031. */
  3032. Vector4.prototype.subtractInPlace = function (otherVector) {
  3033. this.x -= otherVector.x;
  3034. this.y -= otherVector.y;
  3035. this.z -= otherVector.z;
  3036. this.w -= otherVector.w;
  3037. return this;
  3038. };
  3039. /**
  3040. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3041. */
  3042. Vector4.prototype.subtract = function (otherVector) {
  3043. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3044. };
  3045. /**
  3046. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3047. * Returns the current Vector4.
  3048. */
  3049. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3050. result.x = this.x - otherVector.x;
  3051. result.y = this.y - otherVector.y;
  3052. result.z = this.z - otherVector.z;
  3053. result.w = this.w - otherVector.w;
  3054. return this;
  3055. };
  3056. /**
  3057. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3058. */
  3059. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3060. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3061. };
  3062. /**
  3063. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3064. * Returns the current Vector4.
  3065. */
  3066. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3067. result.x = this.x - x;
  3068. result.y = this.y - y;
  3069. result.z = this.z - z;
  3070. result.w = this.w - w;
  3071. return this;
  3072. };
  3073. /**
  3074. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3075. */
  3076. Vector4.prototype.negate = function () {
  3077. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3078. };
  3079. /**
  3080. * Multiplies the current Vector4 coordinates by scale (float).
  3081. * Returns the updated Vector4.
  3082. */
  3083. Vector4.prototype.scaleInPlace = function (scale) {
  3084. this.x *= scale;
  3085. this.y *= scale;
  3086. this.z *= scale;
  3087. this.w *= scale;
  3088. return this;
  3089. };
  3090. /**
  3091. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3092. */
  3093. Vector4.prototype.scale = function (scale) {
  3094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3095. };
  3096. /**
  3097. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3098. * Returns the current Vector4.
  3099. */
  3100. Vector4.prototype.scaleToRef = function (scale, result) {
  3101. result.x = this.x * scale;
  3102. result.y = this.y * scale;
  3103. result.z = this.z * scale;
  3104. result.w = this.w * scale;
  3105. return this;
  3106. };
  3107. /**
  3108. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3109. */
  3110. Vector4.prototype.equals = function (otherVector) {
  3111. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3112. };
  3113. /**
  3114. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3115. */
  3116. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3117. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3118. return otherVector
  3119. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3120. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3121. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3122. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3123. };
  3124. /**
  3125. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3126. */
  3127. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3128. return this.x === x && this.y === y && this.z === z && this.w === w;
  3129. };
  3130. /**
  3131. * Multiplies in place the current Vector4 by the passed one.
  3132. * Returns the updated Vector4.
  3133. */
  3134. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3135. this.x *= otherVector.x;
  3136. this.y *= otherVector.y;
  3137. this.z *= otherVector.z;
  3138. this.w *= otherVector.w;
  3139. return this;
  3140. };
  3141. /**
  3142. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3143. */
  3144. Vector4.prototype.multiply = function (otherVector) {
  3145. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3146. };
  3147. /**
  3148. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3149. * Returns the current Vector4.
  3150. */
  3151. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3152. result.x = this.x * otherVector.x;
  3153. result.y = this.y * otherVector.y;
  3154. result.z = this.z * otherVector.z;
  3155. result.w = this.w * otherVector.w;
  3156. return this;
  3157. };
  3158. /**
  3159. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3160. */
  3161. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3162. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3163. };
  3164. /**
  3165. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3166. */
  3167. Vector4.prototype.divide = function (otherVector) {
  3168. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3169. };
  3170. /**
  3171. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3172. * Returns the current Vector4.
  3173. */
  3174. Vector4.prototype.divideToRef = function (otherVector, result) {
  3175. result.x = this.x / otherVector.x;
  3176. result.y = this.y / otherVector.y;
  3177. result.z = this.z / otherVector.z;
  3178. result.w = this.w / otherVector.w;
  3179. return this;
  3180. };
  3181. /**
  3182. * Divides the current Vector3 coordinates by the passed ones.
  3183. * Returns the updated Vector3.
  3184. */
  3185. Vector4.prototype.divideInPlace = function (otherVector) {
  3186. return this.divideToRef(otherVector, this);
  3187. };
  3188. /**
  3189. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  3190. */
  3191. Vector4.prototype.MinimizeInPlace = function (other) {
  3192. if (other.x < this.x)
  3193. this.x = other.x;
  3194. if (other.y < this.y)
  3195. this.y = other.y;
  3196. if (other.z < this.z)
  3197. this.z = other.z;
  3198. if (other.w < this.w)
  3199. this.w = other.w;
  3200. return this;
  3201. };
  3202. /**
  3203. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3204. */
  3205. Vector4.prototype.MaximizeInPlace = function (other) {
  3206. if (other.x > this.x)
  3207. this.x = other.x;
  3208. if (other.y > this.y)
  3209. this.y = other.y;
  3210. if (other.z > this.z)
  3211. this.z = other.z;
  3212. if (other.w > this.w)
  3213. this.w = other.w;
  3214. return this;
  3215. };
  3216. // Properties
  3217. /**
  3218. * Returns the Vector4 length (float).
  3219. */
  3220. Vector4.prototype.length = function () {
  3221. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3222. };
  3223. /**
  3224. * Returns the Vector4 squared length (float).
  3225. */
  3226. Vector4.prototype.lengthSquared = function () {
  3227. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3228. };
  3229. // Methods
  3230. /**
  3231. * Normalizes in place the Vector4.
  3232. * Returns the updated Vector4.
  3233. */
  3234. Vector4.prototype.normalize = function () {
  3235. var len = this.length();
  3236. if (len === 0)
  3237. return this;
  3238. var num = 1.0 / len;
  3239. this.x *= num;
  3240. this.y *= num;
  3241. this.z *= num;
  3242. this.w *= num;
  3243. return this;
  3244. };
  3245. /**
  3246. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3247. */
  3248. Vector4.prototype.toVector3 = function () {
  3249. return new Vector3(this.x, this.y, this.z);
  3250. };
  3251. /**
  3252. * Returns a new Vector4 copied from the current one.
  3253. */
  3254. Vector4.prototype.clone = function () {
  3255. return new Vector4(this.x, this.y, this.z, this.w);
  3256. };
  3257. /**
  3258. * Updates the current Vector4 with the passed one coordinates.
  3259. * Returns the updated Vector4.
  3260. */
  3261. Vector4.prototype.copyFrom = function (source) {
  3262. this.x = source.x;
  3263. this.y = source.y;
  3264. this.z = source.z;
  3265. this.w = source.w;
  3266. return this;
  3267. };
  3268. /**
  3269. * Updates the current Vector4 coordinates with the passed floats.
  3270. * Returns the updated Vector4.
  3271. */
  3272. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3273. this.x = x;
  3274. this.y = y;
  3275. this.z = z;
  3276. this.w = w;
  3277. return this;
  3278. };
  3279. /**
  3280. * Updates the current Vector4 coordinates with the passed floats.
  3281. * Returns the updated Vector4.
  3282. */
  3283. Vector4.prototype.set = function (x, y, z, w) {
  3284. return this.copyFromFloats(x, y, z, w);
  3285. };
  3286. // Statics
  3287. /**
  3288. * Returns a new Vector4 set from the starting index of the passed array.
  3289. */
  3290. Vector4.FromArray = function (array, offset) {
  3291. if (!offset) {
  3292. offset = 0;
  3293. }
  3294. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3295. };
  3296. /**
  3297. * Updates the passed vector "result" from the starting index of the passed array.
  3298. */
  3299. Vector4.FromArrayToRef = function (array, offset, result) {
  3300. result.x = array[offset];
  3301. result.y = array[offset + 1];
  3302. result.z = array[offset + 2];
  3303. result.w = array[offset + 3];
  3304. };
  3305. /**
  3306. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3307. */
  3308. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3309. Vector4.FromArrayToRef(array, offset, result);
  3310. };
  3311. /**
  3312. * Updates the passed vector "result" coordinates from the passed floats.
  3313. */
  3314. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3315. result.x = x;
  3316. result.y = y;
  3317. result.z = z;
  3318. result.w = w;
  3319. };
  3320. /**
  3321. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3322. */
  3323. Vector4.Zero = function () {
  3324. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3328. */
  3329. Vector4.One = function () {
  3330. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3331. };
  3332. /**
  3333. * Returns a new normalized Vector4 from the passed one.
  3334. */
  3335. Vector4.Normalize = function (vector) {
  3336. var result = Vector4.Zero();
  3337. Vector4.NormalizeToRef(vector, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Updates the passed vector "result" from the normalization of the passed one.
  3342. */
  3343. Vector4.NormalizeToRef = function (vector, result) {
  3344. result.copyFrom(vector);
  3345. result.normalize();
  3346. };
  3347. Vector4.Minimize = function (left, right) {
  3348. var min = left.clone();
  3349. min.MinimizeInPlace(right);
  3350. return min;
  3351. };
  3352. Vector4.Maximize = function (left, right) {
  3353. var max = left.clone();
  3354. max.MaximizeInPlace(right);
  3355. return max;
  3356. };
  3357. /**
  3358. * Returns the distance (float) between the vectors "value1" and "value2".
  3359. */
  3360. Vector4.Distance = function (value1, value2) {
  3361. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3362. };
  3363. /**
  3364. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3365. */
  3366. Vector4.DistanceSquared = function (value1, value2) {
  3367. var x = value1.x - value2.x;
  3368. var y = value1.y - value2.y;
  3369. var z = value1.z - value2.z;
  3370. var w = value1.w - value2.w;
  3371. return (x * x) + (y * y) + (z * z) + (w * w);
  3372. };
  3373. /**
  3374. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3375. */
  3376. Vector4.Center = function (value1, value2) {
  3377. var center = value1.add(value2);
  3378. center.scaleInPlace(0.5);
  3379. return center;
  3380. };
  3381. /**
  3382. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3383. * This methods computes transformed normalized direction vectors only.
  3384. */
  3385. Vector4.TransformNormal = function (vector, transformation) {
  3386. var result = Vector4.Zero();
  3387. Vector4.TransformNormalToRef(vector, transformation, result);
  3388. return result;
  3389. };
  3390. /**
  3391. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3392. * This methods computes transformed normalized direction vectors only.
  3393. */
  3394. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3395. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3396. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3397. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3398. result.x = x;
  3399. result.y = y;
  3400. result.z = z;
  3401. result.w = vector.w;
  3402. };
  3403. /**
  3404. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3405. * This methods computes transformed normalized direction vectors only.
  3406. */
  3407. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3408. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3409. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3410. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3411. result.w = w;
  3412. };
  3413. return Vector4;
  3414. }());
  3415. BABYLON.Vector4 = Vector4;
  3416. var Size = /** @class */ (function () {
  3417. /**
  3418. * Creates a Size object from the passed width and height (floats).
  3419. */
  3420. function Size(width, height) {
  3421. this.width = width;
  3422. this.height = height;
  3423. }
  3424. // Returns a string with the Size width and height.
  3425. Size.prototype.toString = function () {
  3426. return "{W: " + this.width + ", H: " + this.height + "}";
  3427. };
  3428. /**
  3429. * Returns the string "Size"
  3430. */
  3431. Size.prototype.getClassName = function () {
  3432. return "Size";
  3433. };
  3434. /**
  3435. * Returns the Size hash code.
  3436. */
  3437. Size.prototype.getHashCode = function () {
  3438. var hash = this.width || 0;
  3439. hash = (hash * 397) ^ (this.height || 0);
  3440. return hash;
  3441. };
  3442. /**
  3443. * Updates the current size from the passed one.
  3444. * Returns the updated Size.
  3445. */
  3446. Size.prototype.copyFrom = function (src) {
  3447. this.width = src.width;
  3448. this.height = src.height;
  3449. };
  3450. /**
  3451. * Updates in place the current Size from the passed floats.
  3452. * Returns the updated Size.
  3453. */
  3454. Size.prototype.copyFromFloats = function (width, height) {
  3455. this.width = width;
  3456. this.height = height;
  3457. return this;
  3458. };
  3459. /**
  3460. * Updates in place the current Size from the passed floats.
  3461. * Returns the updated Size.
  3462. */
  3463. Size.prototype.set = function (width, height) {
  3464. return this.copyFromFloats(width, height);
  3465. };
  3466. /**
  3467. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3468. */
  3469. Size.prototype.multiplyByFloats = function (w, h) {
  3470. return new Size(this.width * w, this.height * h);
  3471. };
  3472. /**
  3473. * Returns a new Size copied from the passed one.
  3474. */
  3475. Size.prototype.clone = function () {
  3476. return new Size(this.width, this.height);
  3477. };
  3478. /**
  3479. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3480. */
  3481. Size.prototype.equals = function (other) {
  3482. if (!other) {
  3483. return false;
  3484. }
  3485. return (this.width === other.width) && (this.height === other.height);
  3486. };
  3487. Object.defineProperty(Size.prototype, "surface", {
  3488. /**
  3489. * Returns the surface of the Size : width * height (float).
  3490. */
  3491. get: function () {
  3492. return this.width * this.height;
  3493. },
  3494. enumerable: true,
  3495. configurable: true
  3496. });
  3497. /**
  3498. * Returns a new Size set to (0.0, 0.0)
  3499. */
  3500. Size.Zero = function () {
  3501. return new Size(0.0, 0.0);
  3502. };
  3503. /**
  3504. * Returns a new Size set as the addition result of the current Size and the passed one.
  3505. */
  3506. Size.prototype.add = function (otherSize) {
  3507. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3508. return r;
  3509. };
  3510. /**
  3511. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3512. */
  3513. Size.prototype.subtract = function (otherSize) {
  3514. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3515. return r;
  3516. };
  3517. /**
  3518. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3519. */
  3520. Size.Lerp = function (start, end, amount) {
  3521. var w = start.width + ((end.width - start.width) * amount);
  3522. var h = start.height + ((end.height - start.height) * amount);
  3523. return new Size(w, h);
  3524. };
  3525. return Size;
  3526. }());
  3527. BABYLON.Size = Size;
  3528. var Quaternion = /** @class */ (function () {
  3529. /**
  3530. * Creates a new Quaternion from the passed floats.
  3531. */
  3532. function Quaternion(x, y, z, w) {
  3533. if (x === void 0) { x = 0.0; }
  3534. if (y === void 0) { y = 0.0; }
  3535. if (z === void 0) { z = 0.0; }
  3536. if (w === void 0) { w = 1.0; }
  3537. this.x = x;
  3538. this.y = y;
  3539. this.z = z;
  3540. this.w = w;
  3541. }
  3542. /**
  3543. * Returns a string with the Quaternion coordinates.
  3544. */
  3545. Quaternion.prototype.toString = function () {
  3546. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3547. };
  3548. /**
  3549. * Returns the string "Quaternion".
  3550. */
  3551. Quaternion.prototype.getClassName = function () {
  3552. return "Quaternion";
  3553. };
  3554. /**
  3555. * Returns the Quaternion hash code.
  3556. */
  3557. Quaternion.prototype.getHashCode = function () {
  3558. var hash = this.x || 0;
  3559. hash = (hash * 397) ^ (this.y || 0);
  3560. hash = (hash * 397) ^ (this.z || 0);
  3561. hash = (hash * 397) ^ (this.w || 0);
  3562. return hash;
  3563. };
  3564. /**
  3565. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3566. */
  3567. Quaternion.prototype.asArray = function () {
  3568. return [this.x, this.y, this.z, this.w];
  3569. };
  3570. /**
  3571. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3572. */
  3573. Quaternion.prototype.equals = function (otherQuaternion) {
  3574. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3575. };
  3576. /**
  3577. * Returns a new Quaternion copied from the current one.
  3578. */
  3579. Quaternion.prototype.clone = function () {
  3580. return new Quaternion(this.x, this.y, this.z, this.w);
  3581. };
  3582. /**
  3583. * Updates the current Quaternion from the passed one coordinates.
  3584. * Returns the updated Quaterion.
  3585. */
  3586. Quaternion.prototype.copyFrom = function (other) {
  3587. this.x = other.x;
  3588. this.y = other.y;
  3589. this.z = other.z;
  3590. this.w = other.w;
  3591. return this;
  3592. };
  3593. /**
  3594. * Updates the current Quaternion from the passed float coordinates.
  3595. * Returns the updated Quaterion.
  3596. */
  3597. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3598. this.x = x;
  3599. this.y = y;
  3600. this.z = z;
  3601. this.w = w;
  3602. return this;
  3603. };
  3604. /**
  3605. * Updates the current Quaternion from the passed float coordinates.
  3606. * Returns the updated Quaterion.
  3607. */
  3608. Quaternion.prototype.set = function (x, y, z, w) {
  3609. return this.copyFromFloats(x, y, z, w);
  3610. };
  3611. /**
  3612. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3613. */
  3614. Quaternion.prototype.add = function (other) {
  3615. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3616. };
  3617. /**
  3618. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3619. */
  3620. Quaternion.prototype.subtract = function (other) {
  3621. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3622. };
  3623. /**
  3624. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3625. */
  3626. Quaternion.prototype.scale = function (value) {
  3627. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3628. };
  3629. /**
  3630. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3631. */
  3632. Quaternion.prototype.multiply = function (q1) {
  3633. var result = new Quaternion(0, 0, 0, 1.0);
  3634. this.multiplyToRef(q1, result);
  3635. return result;
  3636. };
  3637. /**
  3638. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3639. * Returns the current Quaternion.
  3640. */
  3641. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3642. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3643. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3644. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3645. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3646. result.copyFromFloats(x, y, z, w);
  3647. return this;
  3648. };
  3649. /**
  3650. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3651. * Returns the updated Quaternion.
  3652. */
  3653. Quaternion.prototype.multiplyInPlace = function (q1) {
  3654. this.multiplyToRef(q1, this);
  3655. return this;
  3656. };
  3657. /**
  3658. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3659. * Returns the current Quaternion.
  3660. */
  3661. Quaternion.prototype.conjugateToRef = function (ref) {
  3662. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3663. return this;
  3664. };
  3665. /**
  3666. * Conjugates in place the current Quaternion.
  3667. * Returns the updated Quaternion.
  3668. */
  3669. Quaternion.prototype.conjugateInPlace = function () {
  3670. this.x *= -1;
  3671. this.y *= -1;
  3672. this.z *= -1;
  3673. return this;
  3674. };
  3675. /**
  3676. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3677. */
  3678. Quaternion.prototype.conjugate = function () {
  3679. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3680. return result;
  3681. };
  3682. /**
  3683. * Returns the Quaternion length (float).
  3684. */
  3685. Quaternion.prototype.length = function () {
  3686. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3687. };
  3688. /**
  3689. * Normalize in place the current Quaternion.
  3690. * Returns the updated Quaternion.
  3691. */
  3692. Quaternion.prototype.normalize = function () {
  3693. var length = 1.0 / this.length();
  3694. this.x *= length;
  3695. this.y *= length;
  3696. this.z *= length;
  3697. this.w *= length;
  3698. return this;
  3699. };
  3700. /**
  3701. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3702. */
  3703. Quaternion.prototype.toEulerAngles = function (order) {
  3704. if (order === void 0) { order = "YZX"; }
  3705. var result = Vector3.Zero();
  3706. this.toEulerAnglesToRef(result, order);
  3707. return result;
  3708. };
  3709. /**
  3710. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3711. * Returns the current Quaternion.
  3712. */
  3713. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3714. if (order === void 0) { order = "YZX"; }
  3715. var qz = this.z;
  3716. var qx = this.x;
  3717. var qy = this.y;
  3718. var qw = this.w;
  3719. var sqw = qw * qw;
  3720. var sqz = qz * qz;
  3721. var sqx = qx * qx;
  3722. var sqy = qy * qy;
  3723. var zAxisY = qy * qz - qx * qw;
  3724. var limit = .4999999;
  3725. if (zAxisY < -limit) {
  3726. result.y = 2 * Math.atan2(qy, qw);
  3727. result.x = Math.PI / 2;
  3728. result.z = 0;
  3729. }
  3730. else if (zAxisY > limit) {
  3731. result.y = 2 * Math.atan2(qy, qw);
  3732. result.x = -Math.PI / 2;
  3733. result.z = 0;
  3734. }
  3735. else {
  3736. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3737. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3738. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3739. }
  3740. return this;
  3741. };
  3742. /**
  3743. * Updates the passed rotation matrix with the current Quaternion values.
  3744. * Returns the current Quaternion.
  3745. */
  3746. Quaternion.prototype.toRotationMatrix = function (result) {
  3747. var xx = this.x * this.x;
  3748. var yy = this.y * this.y;
  3749. var zz = this.z * this.z;
  3750. var xy = this.x * this.y;
  3751. var zw = this.z * this.w;
  3752. var zx = this.z * this.x;
  3753. var yw = this.y * this.w;
  3754. var yz = this.y * this.z;
  3755. var xw = this.x * this.w;
  3756. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3757. result.m[1] = 2.0 * (xy + zw);
  3758. result.m[2] = 2.0 * (zx - yw);
  3759. result.m[3] = 0;
  3760. result.m[4] = 2.0 * (xy - zw);
  3761. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3762. result.m[6] = 2.0 * (yz + xw);
  3763. result.m[7] = 0;
  3764. result.m[8] = 2.0 * (zx + yw);
  3765. result.m[9] = 2.0 * (yz - xw);
  3766. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3767. result.m[11] = 0;
  3768. result.m[12] = 0;
  3769. result.m[13] = 0;
  3770. result.m[14] = 0;
  3771. result.m[15] = 1.0;
  3772. result._markAsUpdated();
  3773. return this;
  3774. };
  3775. /**
  3776. * Updates the current Quaternion from the passed rotation matrix values.
  3777. * Returns the updated Quaternion.
  3778. */
  3779. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3780. Quaternion.FromRotationMatrixToRef(matrix, this);
  3781. return this;
  3782. };
  3783. // Statics
  3784. /**
  3785. * Returns a new Quaternion set from the passed rotation matrix values.
  3786. */
  3787. Quaternion.FromRotationMatrix = function (matrix) {
  3788. var result = new Quaternion();
  3789. Quaternion.FromRotationMatrixToRef(matrix, result);
  3790. return result;
  3791. };
  3792. /**
  3793. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3794. */
  3795. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3796. var data = matrix.m;
  3797. var m11 = data[0], m12 = data[4], m13 = data[8];
  3798. var m21 = data[1], m22 = data[5], m23 = data[9];
  3799. var m31 = data[2], m32 = data[6], m33 = data[10];
  3800. var trace = m11 + m22 + m33;
  3801. var s;
  3802. if (trace > 0) {
  3803. s = 0.5 / Math.sqrt(trace + 1.0);
  3804. result.w = 0.25 / s;
  3805. result.x = (m32 - m23) * s;
  3806. result.y = (m13 - m31) * s;
  3807. result.z = (m21 - m12) * s;
  3808. }
  3809. else if (m11 > m22 && m11 > m33) {
  3810. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3811. result.w = (m32 - m23) / s;
  3812. result.x = 0.25 * s;
  3813. result.y = (m12 + m21) / s;
  3814. result.z = (m13 + m31) / s;
  3815. }
  3816. else if (m22 > m33) {
  3817. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3818. result.w = (m13 - m31) / s;
  3819. result.x = (m12 + m21) / s;
  3820. result.y = 0.25 * s;
  3821. result.z = (m23 + m32) / s;
  3822. }
  3823. else {
  3824. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3825. result.w = (m21 - m12) / s;
  3826. result.x = (m13 + m31) / s;
  3827. result.y = (m23 + m32) / s;
  3828. result.z = 0.25 * s;
  3829. }
  3830. };
  3831. /**
  3832. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3833. */
  3834. Quaternion.Zero = function () {
  3835. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3836. };
  3837. /**
  3838. * Returns a new Quaternion as the inverted current Quaternion.
  3839. */
  3840. Quaternion.Inverse = function (q) {
  3841. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3842. };
  3843. /**
  3844. * Returns the identity Quaternion.
  3845. */
  3846. Quaternion.Identity = function () {
  3847. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3848. };
  3849. Quaternion.IsIdentity = function (quaternion) {
  3850. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3851. };
  3852. /**
  3853. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3854. */
  3855. Quaternion.RotationAxis = function (axis, angle) {
  3856. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3857. };
  3858. /**
  3859. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3860. */
  3861. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3862. var sin = Math.sin(angle / 2);
  3863. axis.normalize();
  3864. result.w = Math.cos(angle / 2);
  3865. result.x = axis.x * sin;
  3866. result.y = axis.y * sin;
  3867. result.z = axis.z * sin;
  3868. return result;
  3869. };
  3870. /**
  3871. * Retuns a new Quaternion set from the starting index of the passed array.
  3872. */
  3873. Quaternion.FromArray = function (array, offset) {
  3874. if (!offset) {
  3875. offset = 0;
  3876. }
  3877. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3878. };
  3879. /**
  3880. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3881. */
  3882. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3883. var q = new Quaternion();
  3884. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3885. return q;
  3886. };
  3887. /**
  3888. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3889. */
  3890. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3891. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3892. var halfRoll = roll * 0.5;
  3893. var halfPitch = pitch * 0.5;
  3894. var halfYaw = yaw * 0.5;
  3895. var sinRoll = Math.sin(halfRoll);
  3896. var cosRoll = Math.cos(halfRoll);
  3897. var sinPitch = Math.sin(halfPitch);
  3898. var cosPitch = Math.cos(halfPitch);
  3899. var sinYaw = Math.sin(halfYaw);
  3900. var cosYaw = Math.cos(halfYaw);
  3901. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3902. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3903. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3904. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3905. };
  3906. /**
  3907. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3908. */
  3909. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3910. var result = new Quaternion();
  3911. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3912. return result;
  3913. };
  3914. /**
  3915. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3916. */
  3917. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3918. // Produces a quaternion from Euler angles in the z-x-z orientation
  3919. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3920. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3921. var halfBeta = beta * 0.5;
  3922. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3923. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3924. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3925. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3926. };
  3927. /**
  3928. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3929. * cf to Vector3.RotationFromAxis() documentation.
  3930. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3931. */
  3932. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3933. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3934. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3935. return quat;
  3936. };
  3937. /**
  3938. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3939. * cf to Vector3.RotationFromAxis() documentation.
  3940. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3941. */
  3942. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3943. var rotMat = MathTmp.Matrix[0];
  3944. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3945. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3946. };
  3947. Quaternion.Slerp = function (left, right, amount) {
  3948. var result = Quaternion.Identity();
  3949. Quaternion.SlerpToRef(left, right, amount, result);
  3950. return result;
  3951. };
  3952. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3953. var num2;
  3954. var num3;
  3955. var num = amount;
  3956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3957. var flag = false;
  3958. if (num4 < 0) {
  3959. flag = true;
  3960. num4 = -num4;
  3961. }
  3962. if (num4 > 0.999999) {
  3963. num3 = 1 - num;
  3964. num2 = flag ? -num : num;
  3965. }
  3966. else {
  3967. var num5 = Math.acos(num4);
  3968. var num6 = (1.0 / Math.sin(num5));
  3969. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3970. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3971. }
  3972. result.x = (num3 * left.x) + (num2 * right.x);
  3973. result.y = (num3 * left.y) + (num2 * right.y);
  3974. result.z = (num3 * left.z) + (num2 * right.z);
  3975. result.w = (num3 * left.w) + (num2 * right.w);
  3976. };
  3977. /**
  3978. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3979. */
  3980. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3981. var squared = amount * amount;
  3982. var cubed = amount * squared;
  3983. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3984. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3985. var part3 = (cubed - (2.0 * squared)) + amount;
  3986. var part4 = cubed - squared;
  3987. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3988. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3989. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3990. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3991. return new Quaternion(x, y, z, w);
  3992. };
  3993. return Quaternion;
  3994. }());
  3995. BABYLON.Quaternion = Quaternion;
  3996. var Matrix = /** @class */ (function () {
  3997. function Matrix() {
  3998. this._isIdentity = false;
  3999. this._isIdentityDirty = true;
  4000. this.m = new Float32Array(16);
  4001. this._markAsUpdated();
  4002. }
  4003. Matrix.prototype._markAsUpdated = function () {
  4004. this.updateFlag = Matrix._updateFlagSeed++;
  4005. this._isIdentityDirty = true;
  4006. };
  4007. // Properties
  4008. /**
  4009. * Boolean : True is the matrix is the identity matrix
  4010. */
  4011. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4012. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4013. if (this._isIdentityDirty) {
  4014. this._isIdentityDirty = false;
  4015. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4016. this._isIdentity = false;
  4017. }
  4018. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4019. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4020. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4021. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4022. this._isIdentity = false;
  4023. }
  4024. else {
  4025. this._isIdentity = true;
  4026. }
  4027. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4028. this._isIdentity = false;
  4029. }
  4030. }
  4031. return this._isIdentity;
  4032. };
  4033. /**
  4034. * Returns the matrix determinant (float).
  4035. */
  4036. Matrix.prototype.determinant = function () {
  4037. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4038. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4039. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4040. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4041. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4042. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4043. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4044. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4045. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4046. };
  4047. // Methods
  4048. /**
  4049. * Returns the matrix underlying array.
  4050. */
  4051. Matrix.prototype.toArray = function () {
  4052. return this.m;
  4053. };
  4054. /**
  4055. * Returns the matrix underlying array.
  4056. */
  4057. Matrix.prototype.asArray = function () {
  4058. return this.toArray();
  4059. };
  4060. /**
  4061. * Inverts in place the Matrix.
  4062. * Returns the Matrix inverted.
  4063. */
  4064. Matrix.prototype.invert = function () {
  4065. this.invertToRef(this);
  4066. return this;
  4067. };
  4068. /**
  4069. * Sets all the matrix elements to zero.
  4070. * Returns the Matrix.
  4071. */
  4072. Matrix.prototype.reset = function () {
  4073. for (var index = 0; index < 16; index++) {
  4074. this.m[index] = 0.0;
  4075. }
  4076. this._markAsUpdated();
  4077. return this;
  4078. };
  4079. /**
  4080. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4081. */
  4082. Matrix.prototype.add = function (other) {
  4083. var result = new Matrix();
  4084. this.addToRef(other, result);
  4085. return result;
  4086. };
  4087. /**
  4088. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4089. * Returns the Matrix.
  4090. */
  4091. Matrix.prototype.addToRef = function (other, result) {
  4092. for (var index = 0; index < 16; index++) {
  4093. result.m[index] = this.m[index] + other.m[index];
  4094. }
  4095. result._markAsUpdated();
  4096. return this;
  4097. };
  4098. /**
  4099. * Adds in place the passed matrix to the current Matrix.
  4100. * Returns the updated Matrix.
  4101. */
  4102. Matrix.prototype.addToSelf = function (other) {
  4103. for (var index = 0; index < 16; index++) {
  4104. this.m[index] += other.m[index];
  4105. }
  4106. this._markAsUpdated();
  4107. return this;
  4108. };
  4109. /**
  4110. * Sets the passed matrix with the current inverted Matrix.
  4111. * Returns the unmodified current Matrix.
  4112. */
  4113. Matrix.prototype.invertToRef = function (other) {
  4114. var l1 = this.m[0];
  4115. var l2 = this.m[1];
  4116. var l3 = this.m[2];
  4117. var l4 = this.m[3];
  4118. var l5 = this.m[4];
  4119. var l6 = this.m[5];
  4120. var l7 = this.m[6];
  4121. var l8 = this.m[7];
  4122. var l9 = this.m[8];
  4123. var l10 = this.m[9];
  4124. var l11 = this.m[10];
  4125. var l12 = this.m[11];
  4126. var l13 = this.m[12];
  4127. var l14 = this.m[13];
  4128. var l15 = this.m[14];
  4129. var l16 = this.m[15];
  4130. var l17 = (l11 * l16) - (l12 * l15);
  4131. var l18 = (l10 * l16) - (l12 * l14);
  4132. var l19 = (l10 * l15) - (l11 * l14);
  4133. var l20 = (l9 * l16) - (l12 * l13);
  4134. var l21 = (l9 * l15) - (l11 * l13);
  4135. var l22 = (l9 * l14) - (l10 * l13);
  4136. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4137. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4138. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4139. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4140. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4141. var l28 = (l7 * l16) - (l8 * l15);
  4142. var l29 = (l6 * l16) - (l8 * l14);
  4143. var l30 = (l6 * l15) - (l7 * l14);
  4144. var l31 = (l5 * l16) - (l8 * l13);
  4145. var l32 = (l5 * l15) - (l7 * l13);
  4146. var l33 = (l5 * l14) - (l6 * l13);
  4147. var l34 = (l7 * l12) - (l8 * l11);
  4148. var l35 = (l6 * l12) - (l8 * l10);
  4149. var l36 = (l6 * l11) - (l7 * l10);
  4150. var l37 = (l5 * l12) - (l8 * l9);
  4151. var l38 = (l5 * l11) - (l7 * l9);
  4152. var l39 = (l5 * l10) - (l6 * l9);
  4153. other.m[0] = l23 * l27;
  4154. other.m[4] = l24 * l27;
  4155. other.m[8] = l25 * l27;
  4156. other.m[12] = l26 * l27;
  4157. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4158. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4159. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4160. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4161. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4162. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4163. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4164. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4165. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4166. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4167. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4168. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4169. other._markAsUpdated();
  4170. return this;
  4171. };
  4172. /**
  4173. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4174. * Returns the updated Matrix.
  4175. */
  4176. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4177. this.m[12] = x;
  4178. this.m[13] = y;
  4179. this.m[14] = z;
  4180. this._markAsUpdated();
  4181. return this;
  4182. };
  4183. /**
  4184. * Inserts the translation vector in the current Matrix.
  4185. * Returns the updated Matrix.
  4186. */
  4187. Matrix.prototype.setTranslation = function (vector3) {
  4188. this.m[12] = vector3.x;
  4189. this.m[13] = vector3.y;
  4190. this.m[14] = vector3.z;
  4191. this._markAsUpdated();
  4192. return this;
  4193. };
  4194. /**
  4195. * Returns a new Vector3 as the extracted translation from the Matrix.
  4196. */
  4197. Matrix.prototype.getTranslation = function () {
  4198. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4199. };
  4200. /**
  4201. * Fill a Vector3 with the extracted translation from the Matrix.
  4202. */
  4203. Matrix.prototype.getTranslationToRef = function (result) {
  4204. result.x = this.m[12];
  4205. result.y = this.m[13];
  4206. result.z = this.m[14];
  4207. return this;
  4208. };
  4209. /**
  4210. * Remove rotation and scaling part from the Matrix.
  4211. * Returns the updated Matrix.
  4212. */
  4213. Matrix.prototype.removeRotationAndScaling = function () {
  4214. this.setRowFromFloats(0, 1, 0, 0, 0);
  4215. this.setRowFromFloats(1, 0, 1, 0, 0);
  4216. this.setRowFromFloats(2, 0, 0, 1, 0);
  4217. return this;
  4218. };
  4219. /**
  4220. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4221. */
  4222. Matrix.prototype.multiply = function (other) {
  4223. var result = new Matrix();
  4224. this.multiplyToRef(other, result);
  4225. return result;
  4226. };
  4227. /**
  4228. * Updates the current Matrix from the passed one values.
  4229. * Returns the updated Matrix.
  4230. */
  4231. Matrix.prototype.copyFrom = function (other) {
  4232. for (var index = 0; index < 16; index++) {
  4233. this.m[index] = other.m[index];
  4234. }
  4235. this._markAsUpdated();
  4236. return this;
  4237. };
  4238. /**
  4239. * Populates the passed array from the starting index with the Matrix values.
  4240. * Returns the Matrix.
  4241. */
  4242. Matrix.prototype.copyToArray = function (array, offset) {
  4243. if (offset === void 0) { offset = 0; }
  4244. for (var index = 0; index < 16; index++) {
  4245. array[offset + index] = this.m[index];
  4246. }
  4247. return this;
  4248. };
  4249. /**
  4250. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4251. */
  4252. Matrix.prototype.multiplyToRef = function (other, result) {
  4253. this.multiplyToArray(other, result.m, 0);
  4254. result._markAsUpdated();
  4255. return this;
  4256. };
  4257. /**
  4258. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4259. */
  4260. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4261. var tm0 = this.m[0];
  4262. var tm1 = this.m[1];
  4263. var tm2 = this.m[2];
  4264. var tm3 = this.m[3];
  4265. var tm4 = this.m[4];
  4266. var tm5 = this.m[5];
  4267. var tm6 = this.m[6];
  4268. var tm7 = this.m[7];
  4269. var tm8 = this.m[8];
  4270. var tm9 = this.m[9];
  4271. var tm10 = this.m[10];
  4272. var tm11 = this.m[11];
  4273. var tm12 = this.m[12];
  4274. var tm13 = this.m[13];
  4275. var tm14 = this.m[14];
  4276. var tm15 = this.m[15];
  4277. var om0 = other.m[0];
  4278. var om1 = other.m[1];
  4279. var om2 = other.m[2];
  4280. var om3 = other.m[3];
  4281. var om4 = other.m[4];
  4282. var om5 = other.m[5];
  4283. var om6 = other.m[6];
  4284. var om7 = other.m[7];
  4285. var om8 = other.m[8];
  4286. var om9 = other.m[9];
  4287. var om10 = other.m[10];
  4288. var om11 = other.m[11];
  4289. var om12 = other.m[12];
  4290. var om13 = other.m[13];
  4291. var om14 = other.m[14];
  4292. var om15 = other.m[15];
  4293. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4294. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4295. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4296. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4297. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4298. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4299. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4300. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4301. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4302. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4303. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4304. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4305. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4306. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4307. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4308. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4309. return this;
  4310. };
  4311. /**
  4312. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4313. */
  4314. Matrix.prototype.equals = function (value) {
  4315. return value &&
  4316. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4317. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4318. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4319. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4320. };
  4321. /**
  4322. * Returns a new Matrix from the current Matrix.
  4323. */
  4324. Matrix.prototype.clone = function () {
  4325. 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]);
  4326. };
  4327. /**
  4328. * Returns the string "Matrix"
  4329. */
  4330. Matrix.prototype.getClassName = function () {
  4331. return "Matrix";
  4332. };
  4333. /**
  4334. * Returns the Matrix hash code.
  4335. */
  4336. Matrix.prototype.getHashCode = function () {
  4337. var hash = this.m[0] || 0;
  4338. for (var i = 1; i < 16; i++) {
  4339. hash = (hash * 397) ^ (this.m[i] || 0);
  4340. }
  4341. return hash;
  4342. };
  4343. /**
  4344. * Decomposes the current Matrix into :
  4345. * - a scale vector3 passed as a reference to update,
  4346. * - a rotation quaternion passed as a reference to update,
  4347. * - a translation vector3 passed as a reference to update.
  4348. * Returns the true if operation was successful.
  4349. */
  4350. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4351. translation.x = this.m[12];
  4352. translation.y = this.m[13];
  4353. translation.z = this.m[14];
  4354. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4355. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4356. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4357. if (this.determinant() <= 0) {
  4358. scale.y *= -1;
  4359. }
  4360. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4361. rotation.x = 0;
  4362. rotation.y = 0;
  4363. rotation.z = 0;
  4364. rotation.w = 1;
  4365. return false;
  4366. }
  4367. 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]);
  4368. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4369. return true;
  4370. };
  4371. /**
  4372. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4373. */
  4374. Matrix.prototype.getRotationMatrix = function () {
  4375. var result = Matrix.Identity();
  4376. this.getRotationMatrixToRef(result);
  4377. return result;
  4378. };
  4379. /**
  4380. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4381. * Returns the current Matrix.
  4382. */
  4383. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4384. var m = this.m;
  4385. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4386. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4387. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4388. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4389. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4390. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4391. 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);
  4392. return this;
  4393. };
  4394. // Statics
  4395. /**
  4396. * Returns a new Matrix set from the starting index of the passed array.
  4397. */
  4398. Matrix.FromArray = function (array, offset) {
  4399. var result = new Matrix();
  4400. if (!offset) {
  4401. offset = 0;
  4402. }
  4403. Matrix.FromArrayToRef(array, offset, result);
  4404. return result;
  4405. };
  4406. /**
  4407. * Sets the passed "result" matrix from the starting index of the passed array.
  4408. */
  4409. Matrix.FromArrayToRef = function (array, offset, result) {
  4410. for (var index = 0; index < 16; index++) {
  4411. result.m[index] = array[index + offset];
  4412. }
  4413. result._markAsUpdated();
  4414. };
  4415. /**
  4416. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4417. */
  4418. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4419. for (var index = 0; index < 16; index++) {
  4420. result.m[index] = array[index + offset] * scale;
  4421. }
  4422. result._markAsUpdated();
  4423. };
  4424. /**
  4425. * Sets the passed matrix "result" with the 16 passed floats.
  4426. */
  4427. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4428. result.m[0] = initialM11;
  4429. result.m[1] = initialM12;
  4430. result.m[2] = initialM13;
  4431. result.m[3] = initialM14;
  4432. result.m[4] = initialM21;
  4433. result.m[5] = initialM22;
  4434. result.m[6] = initialM23;
  4435. result.m[7] = initialM24;
  4436. result.m[8] = initialM31;
  4437. result.m[9] = initialM32;
  4438. result.m[10] = initialM33;
  4439. result.m[11] = initialM34;
  4440. result.m[12] = initialM41;
  4441. result.m[13] = initialM42;
  4442. result.m[14] = initialM43;
  4443. result.m[15] = initialM44;
  4444. result._markAsUpdated();
  4445. };
  4446. /**
  4447. * Returns the index-th row of the current matrix as a new Vector4.
  4448. */
  4449. Matrix.prototype.getRow = function (index) {
  4450. if (index < 0 || index > 3) {
  4451. return null;
  4452. }
  4453. var i = index * 4;
  4454. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4455. };
  4456. /**
  4457. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4458. * Returns the updated Matrix.
  4459. */
  4460. Matrix.prototype.setRow = function (index, row) {
  4461. if (index < 0 || index > 3) {
  4462. return this;
  4463. }
  4464. var i = index * 4;
  4465. this.m[i + 0] = row.x;
  4466. this.m[i + 1] = row.y;
  4467. this.m[i + 2] = row.z;
  4468. this.m[i + 3] = row.w;
  4469. this._markAsUpdated();
  4470. return this;
  4471. };
  4472. /**
  4473. * Compute the transpose of the matrix.
  4474. * Returns a new Matrix.
  4475. */
  4476. Matrix.prototype.transpose = function () {
  4477. return Matrix.Transpose(this);
  4478. };
  4479. /**
  4480. * Compute the transpose of the matrix.
  4481. * Returns the current matrix.
  4482. */
  4483. Matrix.prototype.transposeToRef = function (result) {
  4484. Matrix.TransposeToRef(this, result);
  4485. return this;
  4486. };
  4487. /**
  4488. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4489. * Returns the updated Matrix.
  4490. */
  4491. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4492. if (index < 0 || index > 3) {
  4493. return this;
  4494. }
  4495. var i = index * 4;
  4496. this.m[i + 0] = x;
  4497. this.m[i + 1] = y;
  4498. this.m[i + 2] = z;
  4499. this.m[i + 3] = w;
  4500. this._markAsUpdated();
  4501. return this;
  4502. };
  4503. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4504. /**
  4505. * Static identity matrix to be used as readonly matrix
  4506. * Must not be updated.
  4507. */
  4508. get: function () {
  4509. return Matrix._identityReadOnly;
  4510. },
  4511. enumerable: true,
  4512. configurable: true
  4513. });
  4514. /**
  4515. * Returns a new Matrix set from the 16 passed floats.
  4516. */
  4517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4518. var result = new Matrix();
  4519. result.m[0] = initialM11;
  4520. result.m[1] = initialM12;
  4521. result.m[2] = initialM13;
  4522. result.m[3] = initialM14;
  4523. result.m[4] = initialM21;
  4524. result.m[5] = initialM22;
  4525. result.m[6] = initialM23;
  4526. result.m[7] = initialM24;
  4527. result.m[8] = initialM31;
  4528. result.m[9] = initialM32;
  4529. result.m[10] = initialM33;
  4530. result.m[11] = initialM34;
  4531. result.m[12] = initialM41;
  4532. result.m[13] = initialM42;
  4533. result.m[14] = initialM43;
  4534. result.m[15] = initialM44;
  4535. return result;
  4536. };
  4537. /**
  4538. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4539. */
  4540. Matrix.Compose = function (scale, rotation, translation) {
  4541. var result = Matrix.Identity();
  4542. Matrix.ComposeToRef(scale, rotation, translation, result);
  4543. return result;
  4544. };
  4545. /**
  4546. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4547. */
  4548. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4549. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4550. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4551. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4552. result.setTranslation(translation);
  4553. };
  4554. /**
  4555. * Returns a new indentity Matrix.
  4556. */
  4557. Matrix.Identity = function () {
  4558. 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);
  4559. };
  4560. /**
  4561. * Sets the passed "result" as an identity matrix.
  4562. */
  4563. Matrix.IdentityToRef = function (result) {
  4564. 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);
  4565. };
  4566. /**
  4567. * Returns a new zero Matrix.
  4568. */
  4569. Matrix.Zero = function () {
  4570. 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);
  4571. };
  4572. /**
  4573. * Returns a new rotation matrix for "angle" radians around the X axis.
  4574. */
  4575. Matrix.RotationX = function (angle) {
  4576. var result = new Matrix();
  4577. Matrix.RotationXToRef(angle, result);
  4578. return result;
  4579. };
  4580. /**
  4581. * Returns a new Matrix as the passed inverted one.
  4582. */
  4583. Matrix.Invert = function (source) {
  4584. var result = new Matrix();
  4585. source.invertToRef(result);
  4586. return result;
  4587. };
  4588. /**
  4589. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4590. */
  4591. Matrix.RotationXToRef = function (angle, result) {
  4592. var s = Math.sin(angle);
  4593. var c = Math.cos(angle);
  4594. result.m[0] = 1.0;
  4595. result.m[15] = 1.0;
  4596. result.m[5] = c;
  4597. result.m[10] = c;
  4598. result.m[9] = -s;
  4599. result.m[6] = s;
  4600. result.m[1] = 0.0;
  4601. result.m[2] = 0.0;
  4602. result.m[3] = 0.0;
  4603. result.m[4] = 0.0;
  4604. result.m[7] = 0.0;
  4605. result.m[8] = 0.0;
  4606. result.m[11] = 0.0;
  4607. result.m[12] = 0.0;
  4608. result.m[13] = 0.0;
  4609. result.m[14] = 0.0;
  4610. result._markAsUpdated();
  4611. };
  4612. /**
  4613. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4614. */
  4615. Matrix.RotationY = function (angle) {
  4616. var result = new Matrix();
  4617. Matrix.RotationYToRef(angle, result);
  4618. return result;
  4619. };
  4620. /**
  4621. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4622. */
  4623. Matrix.RotationYToRef = function (angle, result) {
  4624. var s = Math.sin(angle);
  4625. var c = Math.cos(angle);
  4626. result.m[5] = 1.0;
  4627. result.m[15] = 1.0;
  4628. result.m[0] = c;
  4629. result.m[2] = -s;
  4630. result.m[8] = s;
  4631. result.m[10] = c;
  4632. result.m[1] = 0.0;
  4633. result.m[3] = 0.0;
  4634. result.m[4] = 0.0;
  4635. result.m[6] = 0.0;
  4636. result.m[7] = 0.0;
  4637. result.m[9] = 0.0;
  4638. result.m[11] = 0.0;
  4639. result.m[12] = 0.0;
  4640. result.m[13] = 0.0;
  4641. result.m[14] = 0.0;
  4642. result._markAsUpdated();
  4643. };
  4644. /**
  4645. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4646. */
  4647. Matrix.RotationZ = function (angle) {
  4648. var result = new Matrix();
  4649. Matrix.RotationZToRef(angle, result);
  4650. return result;
  4651. };
  4652. /**
  4653. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4654. */
  4655. Matrix.RotationZToRef = function (angle, result) {
  4656. var s = Math.sin(angle);
  4657. var c = Math.cos(angle);
  4658. result.m[10] = 1.0;
  4659. result.m[15] = 1.0;
  4660. result.m[0] = c;
  4661. result.m[1] = s;
  4662. result.m[4] = -s;
  4663. result.m[5] = c;
  4664. result.m[2] = 0.0;
  4665. result.m[3] = 0.0;
  4666. result.m[6] = 0.0;
  4667. result.m[7] = 0.0;
  4668. result.m[8] = 0.0;
  4669. result.m[9] = 0.0;
  4670. result.m[11] = 0.0;
  4671. result.m[12] = 0.0;
  4672. result.m[13] = 0.0;
  4673. result.m[14] = 0.0;
  4674. result._markAsUpdated();
  4675. };
  4676. /**
  4677. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4678. */
  4679. Matrix.RotationAxis = function (axis, angle) {
  4680. var result = Matrix.Zero();
  4681. Matrix.RotationAxisToRef(axis, angle, result);
  4682. return result;
  4683. };
  4684. /**
  4685. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4686. */
  4687. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4688. var s = Math.sin(-angle);
  4689. var c = Math.cos(-angle);
  4690. var c1 = 1 - c;
  4691. axis.normalize();
  4692. result.m[0] = (axis.x * axis.x) * c1 + c;
  4693. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4694. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4695. result.m[3] = 0.0;
  4696. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4697. result.m[5] = (axis.y * axis.y) * c1 + c;
  4698. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4699. result.m[7] = 0.0;
  4700. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4701. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4702. result.m[10] = (axis.z * axis.z) * c1 + c;
  4703. result.m[11] = 0.0;
  4704. result.m[15] = 1.0;
  4705. result._markAsUpdated();
  4706. };
  4707. /**
  4708. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4709. */
  4710. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4711. var result = new Matrix();
  4712. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4713. return result;
  4714. };
  4715. /**
  4716. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4717. */
  4718. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4719. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4720. this._tempQuaternion.toRotationMatrix(result);
  4721. };
  4722. /**
  4723. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4724. */
  4725. Matrix.Scaling = function (x, y, z) {
  4726. var result = Matrix.Zero();
  4727. Matrix.ScalingToRef(x, y, z, result);
  4728. return result;
  4729. };
  4730. /**
  4731. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4732. */
  4733. Matrix.ScalingToRef = function (x, y, z, result) {
  4734. result.m[0] = x;
  4735. result.m[1] = 0.0;
  4736. result.m[2] = 0.0;
  4737. result.m[3] = 0.0;
  4738. result.m[4] = 0.0;
  4739. result.m[5] = y;
  4740. result.m[6] = 0.0;
  4741. result.m[7] = 0.0;
  4742. result.m[8] = 0.0;
  4743. result.m[9] = 0.0;
  4744. result.m[10] = z;
  4745. result.m[11] = 0.0;
  4746. result.m[12] = 0.0;
  4747. result.m[13] = 0.0;
  4748. result.m[14] = 0.0;
  4749. result.m[15] = 1.0;
  4750. result._markAsUpdated();
  4751. };
  4752. /**
  4753. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4754. */
  4755. Matrix.Translation = function (x, y, z) {
  4756. var result = Matrix.Identity();
  4757. Matrix.TranslationToRef(x, y, z, result);
  4758. return result;
  4759. };
  4760. /**
  4761. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4762. */
  4763. Matrix.TranslationToRef = function (x, y, z, result) {
  4764. 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);
  4765. };
  4766. /**
  4767. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4768. */
  4769. Matrix.Lerp = function (startValue, endValue, gradient) {
  4770. var result = Matrix.Zero();
  4771. for (var index = 0; index < 16; index++) {
  4772. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4773. }
  4774. result._markAsUpdated();
  4775. return result;
  4776. };
  4777. /**
  4778. * Returns a new Matrix whose values are computed by :
  4779. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4780. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4781. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4782. */
  4783. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4784. var startScale = new Vector3(0, 0, 0);
  4785. var startRotation = new Quaternion();
  4786. var startTranslation = new Vector3(0, 0, 0);
  4787. startValue.decompose(startScale, startRotation, startTranslation);
  4788. var endScale = new Vector3(0, 0, 0);
  4789. var endRotation = new Quaternion();
  4790. var endTranslation = new Vector3(0, 0, 0);
  4791. endValue.decompose(endScale, endRotation, endTranslation);
  4792. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4793. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4794. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4795. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4796. };
  4797. /**
  4798. * 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".
  4799. * This methods works for a Left-Handed system.
  4800. */
  4801. Matrix.LookAtLH = function (eye, target, up) {
  4802. var result = Matrix.Zero();
  4803. Matrix.LookAtLHToRef(eye, target, up, result);
  4804. return result;
  4805. };
  4806. /**
  4807. * 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".
  4808. * This methods works for a Left-Handed system.
  4809. */
  4810. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4811. // Z axis
  4812. target.subtractToRef(eye, this._zAxis);
  4813. this._zAxis.normalize();
  4814. // X axis
  4815. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4816. if (this._xAxis.lengthSquared() === 0) {
  4817. this._xAxis.x = 1.0;
  4818. }
  4819. else {
  4820. this._xAxis.normalize();
  4821. }
  4822. // Y axis
  4823. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4824. this._yAxis.normalize();
  4825. // Eye angles
  4826. var ex = -Vector3.Dot(this._xAxis, eye);
  4827. var ey = -Vector3.Dot(this._yAxis, eye);
  4828. var ez = -Vector3.Dot(this._zAxis, eye);
  4829. 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);
  4830. };
  4831. /**
  4832. * 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".
  4833. * This methods works for a Right-Handed system.
  4834. */
  4835. Matrix.LookAtRH = function (eye, target, up) {
  4836. var result = Matrix.Zero();
  4837. Matrix.LookAtRHToRef(eye, target, up, result);
  4838. return result;
  4839. };
  4840. /**
  4841. * 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".
  4842. * This methods works for a Left-Handed system.
  4843. */
  4844. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4845. // Z axis
  4846. eye.subtractToRef(target, this._zAxis);
  4847. this._zAxis.normalize();
  4848. // X axis
  4849. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4850. if (this._xAxis.lengthSquared() === 0) {
  4851. this._xAxis.x = 1.0;
  4852. }
  4853. else {
  4854. this._xAxis.normalize();
  4855. }
  4856. // Y axis
  4857. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4858. this._yAxis.normalize();
  4859. // Eye angles
  4860. var ex = -Vector3.Dot(this._xAxis, eye);
  4861. var ey = -Vector3.Dot(this._yAxis, eye);
  4862. var ez = -Vector3.Dot(this._zAxis, eye);
  4863. 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);
  4864. };
  4865. /**
  4866. * 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.
  4867. */
  4868. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4869. var matrix = Matrix.Zero();
  4870. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4871. return matrix;
  4872. };
  4873. /**
  4874. * 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.
  4875. */
  4876. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4877. var n = znear;
  4878. var f = zfar;
  4879. var a = 2.0 / width;
  4880. var b = 2.0 / height;
  4881. var c = 2.0 / (f - n);
  4882. var d = -(f + n) / (f - n);
  4883. 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);
  4884. };
  4885. /**
  4886. * 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.
  4887. */
  4888. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4889. var matrix = Matrix.Zero();
  4890. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4891. return matrix;
  4892. };
  4893. /**
  4894. * 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.
  4895. */
  4896. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4897. var n = znear;
  4898. var f = zfar;
  4899. var a = 2.0 / (right - left);
  4900. var b = 2.0 / (top - bottom);
  4901. var c = 2.0 / (f - n);
  4902. var d = -(f + n) / (f - n);
  4903. var i0 = (left + right) / (left - right);
  4904. var i1 = (top + bottom) / (bottom - top);
  4905. 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);
  4906. };
  4907. /**
  4908. * 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.
  4909. */
  4910. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4911. var matrix = Matrix.Zero();
  4912. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4913. return matrix;
  4914. };
  4915. /**
  4916. * 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.
  4917. */
  4918. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4919. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4920. result.m[10] *= -1.0;
  4921. };
  4922. /**
  4923. * 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.
  4924. */
  4925. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4926. var matrix = Matrix.Zero();
  4927. var n = znear;
  4928. var f = zfar;
  4929. var a = 2.0 * n / width;
  4930. var b = 2.0 * n / height;
  4931. var c = (f + n) / (f - n);
  4932. var d = -2.0 * f * n / (f - n);
  4933. 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);
  4934. return matrix;
  4935. };
  4936. /**
  4937. * 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.
  4938. */
  4939. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4940. var matrix = Matrix.Zero();
  4941. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4942. return matrix;
  4943. };
  4944. /**
  4945. * 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.
  4946. */
  4947. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4948. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4949. var n = znear;
  4950. var f = zfar;
  4951. var t = 1.0 / (Math.tan(fov * 0.5));
  4952. var a = isVerticalFovFixed ? (t / aspect) : t;
  4953. var b = isVerticalFovFixed ? t : (t * aspect);
  4954. var c = (f + n) / (f - n);
  4955. var d = -2.0 * f * n / (f - n);
  4956. 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);
  4957. };
  4958. /**
  4959. * 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.
  4960. */
  4961. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4962. var matrix = Matrix.Zero();
  4963. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4964. return matrix;
  4965. };
  4966. /**
  4967. * 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.
  4968. */
  4969. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4970. //alternatively this could be expressed as:
  4971. // m = PerspectiveFovLHToRef
  4972. // m[10] *= -1.0;
  4973. // m[11] *= -1.0;
  4974. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4975. var n = znear;
  4976. var f = zfar;
  4977. var t = 1.0 / (Math.tan(fov * 0.5));
  4978. var a = isVerticalFovFixed ? (t / aspect) : t;
  4979. var b = isVerticalFovFixed ? t : (t * aspect);
  4980. var c = -(f + n) / (f - n);
  4981. var d = -2 * f * n / (f - n);
  4982. 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);
  4983. };
  4984. /**
  4985. * 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.
  4986. */
  4987. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4988. if (rightHanded === void 0) { rightHanded = false; }
  4989. var rightHandedFactor = rightHanded ? -1 : 1;
  4990. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4991. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4992. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4993. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4994. var xScale = 2.0 / (leftTan + rightTan);
  4995. var yScale = 2.0 / (upTan + downTan);
  4996. result.m[0] = xScale;
  4997. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4998. result.m[5] = yScale;
  4999. result.m[6] = result.m[7] = 0.0;
  5000. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5001. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5002. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5003. result.m[10] = -zfar / (znear - zfar);
  5004. result.m[11] = 1.0 * rightHandedFactor;
  5005. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5006. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5007. // result.m[14] = (znear * zfar) / (znear - zfar);
  5008. result._markAsUpdated();
  5009. };
  5010. /**
  5011. * Returns the final transformation matrix : world * view * projection * viewport
  5012. */
  5013. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5014. var cw = viewport.width;
  5015. var ch = viewport.height;
  5016. var cx = viewport.x;
  5017. var cy = viewport.y;
  5018. 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);
  5019. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5020. };
  5021. /**
  5022. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5023. */
  5024. Matrix.GetAsMatrix2x2 = function (matrix) {
  5025. return new Float32Array([
  5026. matrix.m[0], matrix.m[1],
  5027. matrix.m[4], matrix.m[5]
  5028. ]);
  5029. };
  5030. /**
  5031. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5032. */
  5033. Matrix.GetAsMatrix3x3 = function (matrix) {
  5034. return new Float32Array([
  5035. matrix.m[0], matrix.m[1], matrix.m[2],
  5036. matrix.m[4], matrix.m[5], matrix.m[6],
  5037. matrix.m[8], matrix.m[9], matrix.m[10]
  5038. ]);
  5039. };
  5040. /**
  5041. * Compute the transpose of the passed Matrix.
  5042. * Returns a new Matrix.
  5043. */
  5044. Matrix.Transpose = function (matrix) {
  5045. var result = new Matrix();
  5046. Matrix.TransposeToRef(matrix, result);
  5047. return result;
  5048. };
  5049. /**
  5050. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5051. */
  5052. Matrix.TransposeToRef = function (matrix, result) {
  5053. result.m[0] = matrix.m[0];
  5054. result.m[1] = matrix.m[4];
  5055. result.m[2] = matrix.m[8];
  5056. result.m[3] = matrix.m[12];
  5057. result.m[4] = matrix.m[1];
  5058. result.m[5] = matrix.m[5];
  5059. result.m[6] = matrix.m[9];
  5060. result.m[7] = matrix.m[13];
  5061. result.m[8] = matrix.m[2];
  5062. result.m[9] = matrix.m[6];
  5063. result.m[10] = matrix.m[10];
  5064. result.m[11] = matrix.m[14];
  5065. result.m[12] = matrix.m[3];
  5066. result.m[13] = matrix.m[7];
  5067. result.m[14] = matrix.m[11];
  5068. result.m[15] = matrix.m[15];
  5069. };
  5070. /**
  5071. * Returns a new Matrix as the reflection matrix across the passed plane.
  5072. */
  5073. Matrix.Reflection = function (plane) {
  5074. var matrix = new Matrix();
  5075. Matrix.ReflectionToRef(plane, matrix);
  5076. return matrix;
  5077. };
  5078. /**
  5079. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5080. */
  5081. Matrix.ReflectionToRef = function (plane, result) {
  5082. plane.normalize();
  5083. var x = plane.normal.x;
  5084. var y = plane.normal.y;
  5085. var z = plane.normal.z;
  5086. var temp = -2 * x;
  5087. var temp2 = -2 * y;
  5088. var temp3 = -2 * z;
  5089. result.m[0] = (temp * x) + 1;
  5090. result.m[1] = temp2 * x;
  5091. result.m[2] = temp3 * x;
  5092. result.m[3] = 0.0;
  5093. result.m[4] = temp * y;
  5094. result.m[5] = (temp2 * y) + 1;
  5095. result.m[6] = temp3 * y;
  5096. result.m[7] = 0.0;
  5097. result.m[8] = temp * z;
  5098. result.m[9] = temp2 * z;
  5099. result.m[10] = (temp3 * z) + 1;
  5100. result.m[11] = 0.0;
  5101. result.m[12] = temp * plane.d;
  5102. result.m[13] = temp2 * plane.d;
  5103. result.m[14] = temp3 * plane.d;
  5104. result.m[15] = 1.0;
  5105. result._markAsUpdated();
  5106. };
  5107. /**
  5108. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5109. */
  5110. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5111. result.m[0] = xaxis.x;
  5112. result.m[1] = xaxis.y;
  5113. result.m[2] = xaxis.z;
  5114. result.m[3] = 0.0;
  5115. result.m[4] = yaxis.x;
  5116. result.m[5] = yaxis.y;
  5117. result.m[6] = yaxis.z;
  5118. result.m[7] = 0.0;
  5119. result.m[8] = zaxis.x;
  5120. result.m[9] = zaxis.y;
  5121. result.m[10] = zaxis.z;
  5122. result.m[11] = 0.0;
  5123. result.m[12] = 0.0;
  5124. result.m[13] = 0.0;
  5125. result.m[14] = 0.0;
  5126. result.m[15] = 1.0;
  5127. result._markAsUpdated();
  5128. };
  5129. /**
  5130. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5131. */
  5132. Matrix.FromQuaternionToRef = function (quat, result) {
  5133. var xx = quat.x * quat.x;
  5134. var yy = quat.y * quat.y;
  5135. var zz = quat.z * quat.z;
  5136. var xy = quat.x * quat.y;
  5137. var zw = quat.z * quat.w;
  5138. var zx = quat.z * quat.x;
  5139. var yw = quat.y * quat.w;
  5140. var yz = quat.y * quat.z;
  5141. var xw = quat.x * quat.w;
  5142. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5143. result.m[1] = 2.0 * (xy + zw);
  5144. result.m[2] = 2.0 * (zx - yw);
  5145. result.m[3] = 0.0;
  5146. result.m[4] = 2.0 * (xy - zw);
  5147. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5148. result.m[6] = 2.0 * (yz + xw);
  5149. result.m[7] = 0.0;
  5150. result.m[8] = 2.0 * (zx + yw);
  5151. result.m[9] = 2.0 * (yz - xw);
  5152. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5153. result.m[11] = 0.0;
  5154. result.m[12] = 0.0;
  5155. result.m[13] = 0.0;
  5156. result.m[14] = 0.0;
  5157. result.m[15] = 1.0;
  5158. result._markAsUpdated();
  5159. };
  5160. Matrix._tempQuaternion = new Quaternion();
  5161. Matrix._xAxis = Vector3.Zero();
  5162. Matrix._yAxis = Vector3.Zero();
  5163. Matrix._zAxis = Vector3.Zero();
  5164. Matrix._updateFlagSeed = 0;
  5165. Matrix._identityReadOnly = Matrix.Identity();
  5166. return Matrix;
  5167. }());
  5168. BABYLON.Matrix = Matrix;
  5169. var Plane = /** @class */ (function () {
  5170. /**
  5171. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5172. */
  5173. function Plane(a, b, c, d) {
  5174. this.normal = new Vector3(a, b, c);
  5175. this.d = d;
  5176. }
  5177. /**
  5178. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5179. */
  5180. Plane.prototype.asArray = function () {
  5181. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5182. };
  5183. // Methods
  5184. /**
  5185. * Returns a new plane copied from the current Plane.
  5186. */
  5187. Plane.prototype.clone = function () {
  5188. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5189. };
  5190. /**
  5191. * Returns the string "Plane".
  5192. */
  5193. Plane.prototype.getClassName = function () {
  5194. return "Plane";
  5195. };
  5196. /**
  5197. * Returns the Plane hash code.
  5198. */
  5199. Plane.prototype.getHashCode = function () {
  5200. var hash = this.normal.getHashCode();
  5201. hash = (hash * 397) ^ (this.d || 0);
  5202. return hash;
  5203. };
  5204. /**
  5205. * Normalize the current Plane in place.
  5206. * Returns the updated Plane.
  5207. */
  5208. Plane.prototype.normalize = function () {
  5209. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5210. var magnitude = 0.0;
  5211. if (norm !== 0) {
  5212. magnitude = 1.0 / norm;
  5213. }
  5214. this.normal.x *= magnitude;
  5215. this.normal.y *= magnitude;
  5216. this.normal.z *= magnitude;
  5217. this.d *= magnitude;
  5218. return this;
  5219. };
  5220. /**
  5221. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5222. */
  5223. Plane.prototype.transform = function (transformation) {
  5224. var transposedMatrix = Matrix.Transpose(transformation);
  5225. var x = this.normal.x;
  5226. var y = this.normal.y;
  5227. var z = this.normal.z;
  5228. var d = this.d;
  5229. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5230. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5231. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5232. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5233. return new Plane(normalX, normalY, normalZ, finalD);
  5234. };
  5235. /**
  5236. * Returns the dot product (float) of the point coordinates and the plane normal.
  5237. */
  5238. Plane.prototype.dotCoordinate = function (point) {
  5239. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5240. };
  5241. /**
  5242. * Updates the current Plane from the plane defined by the three passed points.
  5243. * Returns the updated Plane.
  5244. */
  5245. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5246. var x1 = point2.x - point1.x;
  5247. var y1 = point2.y - point1.y;
  5248. var z1 = point2.z - point1.z;
  5249. var x2 = point3.x - point1.x;
  5250. var y2 = point3.y - point1.y;
  5251. var z2 = point3.z - point1.z;
  5252. var yz = (y1 * z2) - (z1 * y2);
  5253. var xz = (z1 * x2) - (x1 * z2);
  5254. var xy = (x1 * y2) - (y1 * x2);
  5255. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5256. var invPyth;
  5257. if (pyth !== 0) {
  5258. invPyth = 1.0 / pyth;
  5259. }
  5260. else {
  5261. invPyth = 0.0;
  5262. }
  5263. this.normal.x = yz * invPyth;
  5264. this.normal.y = xz * invPyth;
  5265. this.normal.z = xy * invPyth;
  5266. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5267. return this;
  5268. };
  5269. /**
  5270. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5271. */
  5272. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5273. var dot = Vector3.Dot(this.normal, direction);
  5274. return (dot <= epsilon);
  5275. };
  5276. /**
  5277. * Returns the signed distance (float) from the passed point to the Plane.
  5278. */
  5279. Plane.prototype.signedDistanceTo = function (point) {
  5280. return Vector3.Dot(point, this.normal) + this.d;
  5281. };
  5282. // Statics
  5283. /**
  5284. * Returns a new Plane from the passed array.
  5285. */
  5286. Plane.FromArray = function (array) {
  5287. return new Plane(array[0], array[1], array[2], array[3]);
  5288. };
  5289. /**
  5290. * Returns a new Plane defined by the three passed points.
  5291. */
  5292. Plane.FromPoints = function (point1, point2, point3) {
  5293. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5294. result.copyFromPoints(point1, point2, point3);
  5295. return result;
  5296. };
  5297. /**
  5298. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5299. * Note : the vector "normal" is updated because normalized.
  5300. */
  5301. Plane.FromPositionAndNormal = function (origin, normal) {
  5302. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5303. normal.normalize();
  5304. result.normal = normal;
  5305. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5306. return result;
  5307. };
  5308. /**
  5309. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5310. */
  5311. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5312. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5313. return Vector3.Dot(point, normal) + d;
  5314. };
  5315. return Plane;
  5316. }());
  5317. BABYLON.Plane = Plane;
  5318. var Viewport = /** @class */ (function () {
  5319. /**
  5320. * Creates a Viewport object located at (x, y) and sized (width, height).
  5321. */
  5322. function Viewport(x, y, width, height) {
  5323. this.x = x;
  5324. this.y = y;
  5325. this.width = width;
  5326. this.height = height;
  5327. }
  5328. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5329. if (renderWidthOrEngine.getRenderWidth) {
  5330. var engine = renderWidthOrEngine;
  5331. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5332. }
  5333. var renderWidth = renderWidthOrEngine;
  5334. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5335. };
  5336. /**
  5337. * Returns a new Viewport copied from the current one.
  5338. */
  5339. Viewport.prototype.clone = function () {
  5340. return new Viewport(this.x, this.y, this.width, this.height);
  5341. };
  5342. return Viewport;
  5343. }());
  5344. BABYLON.Viewport = Viewport;
  5345. var Frustum = /** @class */ (function () {
  5346. function Frustum() {
  5347. }
  5348. /**
  5349. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5350. */
  5351. Frustum.GetPlanes = function (transform) {
  5352. var frustumPlanes = [];
  5353. for (var index = 0; index < 6; index++) {
  5354. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5355. }
  5356. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5357. return frustumPlanes;
  5358. };
  5359. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5360. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5361. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5362. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5363. frustumPlane.d = transform.m[15] + transform.m[14];
  5364. frustumPlane.normalize();
  5365. };
  5366. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5367. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5368. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5369. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5370. frustumPlane.d = transform.m[15] - transform.m[14];
  5371. frustumPlane.normalize();
  5372. };
  5373. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5374. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5375. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5376. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5377. frustumPlane.d = transform.m[15] + transform.m[12];
  5378. frustumPlane.normalize();
  5379. };
  5380. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5381. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5382. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5383. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5384. frustumPlane.d = transform.m[15] - transform.m[12];
  5385. frustumPlane.normalize();
  5386. };
  5387. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5388. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5389. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5390. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5391. frustumPlane.d = transform.m[15] - transform.m[13];
  5392. frustumPlane.normalize();
  5393. };
  5394. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5395. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5396. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5397. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5398. frustumPlane.d = transform.m[15] + transform.m[13];
  5399. frustumPlane.normalize();
  5400. };
  5401. /**
  5402. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5403. */
  5404. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5405. // Near
  5406. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5407. // Far
  5408. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5409. // Left
  5410. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5411. // Right
  5412. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5413. // Top
  5414. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5415. // Bottom
  5416. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5417. };
  5418. return Frustum;
  5419. }());
  5420. BABYLON.Frustum = Frustum;
  5421. var Space;
  5422. (function (Space) {
  5423. Space[Space["LOCAL"] = 0] = "LOCAL";
  5424. Space[Space["WORLD"] = 1] = "WORLD";
  5425. Space[Space["BONE"] = 2] = "BONE";
  5426. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5427. var Axis = /** @class */ (function () {
  5428. function Axis() {
  5429. }
  5430. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5431. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5432. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5433. return Axis;
  5434. }());
  5435. BABYLON.Axis = Axis;
  5436. ;
  5437. var BezierCurve = /** @class */ (function () {
  5438. function BezierCurve() {
  5439. }
  5440. /**
  5441. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5442. */
  5443. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5444. // Extract X (which is equal to time here)
  5445. var f0 = 1 - 3 * x2 + 3 * x1;
  5446. var f1 = 3 * x2 - 6 * x1;
  5447. var f2 = 3 * x1;
  5448. var refinedT = t;
  5449. for (var i = 0; i < 5; i++) {
  5450. var refinedT2 = refinedT * refinedT;
  5451. var refinedT3 = refinedT2 * refinedT;
  5452. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5453. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5454. refinedT -= (x - t) * slope;
  5455. refinedT = Math.min(1, Math.max(0, refinedT));
  5456. }
  5457. // Resolve cubic bezier for the given x
  5458. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5459. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5460. Math.pow(refinedT, 3);
  5461. };
  5462. return BezierCurve;
  5463. }());
  5464. BABYLON.BezierCurve = BezierCurve;
  5465. var Orientation;
  5466. (function (Orientation) {
  5467. Orientation[Orientation["CW"] = 0] = "CW";
  5468. Orientation[Orientation["CCW"] = 1] = "CCW";
  5469. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5470. var Angle = /** @class */ (function () {
  5471. /**
  5472. * Creates an Angle object of "radians" radians (float).
  5473. */
  5474. function Angle(radians) {
  5475. var _this = this;
  5476. /**
  5477. * Returns the Angle value in degrees (float).
  5478. */
  5479. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5480. /**
  5481. * Returns the Angle value in radians (float).
  5482. */
  5483. this.radians = function () { return _this._radians; };
  5484. this._radians = radians;
  5485. if (this._radians < 0.0)
  5486. this._radians += (2.0 * Math.PI);
  5487. }
  5488. /**
  5489. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5490. */
  5491. Angle.BetweenTwoPoints = function (a, b) {
  5492. var delta = b.subtract(a);
  5493. var theta = Math.atan2(delta.y, delta.x);
  5494. return new Angle(theta);
  5495. };
  5496. /**
  5497. * Returns a new Angle object from the passed float in radians.
  5498. */
  5499. Angle.FromRadians = function (radians) {
  5500. return new Angle(radians);
  5501. };
  5502. /**
  5503. * Returns a new Angle object from the passed float in degrees.
  5504. */
  5505. Angle.FromDegrees = function (degrees) {
  5506. return new Angle(degrees * Math.PI / 180.0);
  5507. };
  5508. return Angle;
  5509. }());
  5510. BABYLON.Angle = Angle;
  5511. var Arc2 = /** @class */ (function () {
  5512. /**
  5513. * Creates an Arc object from the three passed points : start, middle and end.
  5514. */
  5515. function Arc2(startPoint, midPoint, endPoint) {
  5516. this.startPoint = startPoint;
  5517. this.midPoint = midPoint;
  5518. this.endPoint = endPoint;
  5519. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5520. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5521. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5522. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5523. 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);
  5524. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5525. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5526. var a1 = this.startAngle.degrees();
  5527. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5528. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5529. // angles correction
  5530. if (a2 - a1 > +180.0)
  5531. a2 -= 360.0;
  5532. if (a2 - a1 < -180.0)
  5533. a2 += 360.0;
  5534. if (a3 - a2 > +180.0)
  5535. a3 -= 360.0;
  5536. if (a3 - a2 < -180.0)
  5537. a3 += 360.0;
  5538. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5539. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5540. }
  5541. return Arc2;
  5542. }());
  5543. BABYLON.Arc2 = Arc2;
  5544. var Path2 = /** @class */ (function () {
  5545. /**
  5546. * Creates a Path2 object from the starting 2D coordinates x and y.
  5547. */
  5548. function Path2(x, y) {
  5549. this._points = new Array();
  5550. this._length = 0.0;
  5551. this.closed = false;
  5552. this._points.push(new Vector2(x, y));
  5553. }
  5554. /**
  5555. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5556. * Returns the updated Path2.
  5557. */
  5558. Path2.prototype.addLineTo = function (x, y) {
  5559. if (this.closed) {
  5560. //Tools.Error("cannot add lines to closed paths");
  5561. return this;
  5562. }
  5563. var newPoint = new Vector2(x, y);
  5564. var previousPoint = this._points[this._points.length - 1];
  5565. this._points.push(newPoint);
  5566. this._length += newPoint.subtract(previousPoint).length();
  5567. return this;
  5568. };
  5569. /**
  5570. * 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.
  5571. * Returns the updated Path2.
  5572. */
  5573. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5574. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5575. if (this.closed) {
  5576. //Tools.Error("cannot add arcs to closed paths");
  5577. return this;
  5578. }
  5579. var startPoint = this._points[this._points.length - 1];
  5580. var midPoint = new Vector2(midX, midY);
  5581. var endPoint = new Vector2(endX, endY);
  5582. var arc = new Arc2(startPoint, midPoint, endPoint);
  5583. var increment = arc.angle.radians() / numberOfSegments;
  5584. if (arc.orientation === Orientation.CW)
  5585. increment *= -1;
  5586. var currentAngle = arc.startAngle.radians() + increment;
  5587. for (var i = 0; i < numberOfSegments; i++) {
  5588. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5589. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5590. this.addLineTo(x, y);
  5591. currentAngle += increment;
  5592. }
  5593. return this;
  5594. };
  5595. /**
  5596. * Closes the Path2.
  5597. * Returns the Path2.
  5598. */
  5599. Path2.prototype.close = function () {
  5600. this.closed = true;
  5601. return this;
  5602. };
  5603. /**
  5604. * Returns the Path2 total length (float).
  5605. */
  5606. Path2.prototype.length = function () {
  5607. var result = this._length;
  5608. if (!this.closed) {
  5609. var lastPoint = this._points[this._points.length - 1];
  5610. var firstPoint = this._points[0];
  5611. result += (firstPoint.subtract(lastPoint).length());
  5612. }
  5613. return result;
  5614. };
  5615. /**
  5616. * Returns the Path2 internal array of points.
  5617. */
  5618. Path2.prototype.getPoints = function () {
  5619. return this._points;
  5620. };
  5621. /**
  5622. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5623. */
  5624. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5625. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5626. //Tools.Error("normalized length position should be between 0 and 1.");
  5627. return Vector2.Zero();
  5628. }
  5629. var lengthPosition = normalizedLengthPosition * this.length();
  5630. var previousOffset = 0;
  5631. for (var i = 0; i < this._points.length; i++) {
  5632. var j = (i + 1) % this._points.length;
  5633. var a = this._points[i];
  5634. var b = this._points[j];
  5635. var bToA = b.subtract(a);
  5636. var nextOffset = (bToA.length() + previousOffset);
  5637. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5638. var dir = bToA.normalize();
  5639. var localOffset = lengthPosition - previousOffset;
  5640. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5641. }
  5642. previousOffset = nextOffset;
  5643. }
  5644. //Tools.Error("internal error");
  5645. return Vector2.Zero();
  5646. };
  5647. /**
  5648. * Returns a new Path2 starting at the coordinates (x, y).
  5649. */
  5650. Path2.StartingAt = function (x, y) {
  5651. return new Path2(x, y);
  5652. };
  5653. return Path2;
  5654. }());
  5655. BABYLON.Path2 = Path2;
  5656. var Path3D = /** @class */ (function () {
  5657. /**
  5658. * new Path3D(path, normal, raw)
  5659. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5660. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5661. * path : an array of Vector3, the curve axis of the Path3D
  5662. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5663. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5664. */
  5665. function Path3D(path, firstNormal, raw) {
  5666. if (firstNormal === void 0) { firstNormal = null; }
  5667. this.path = path;
  5668. this._curve = new Array();
  5669. this._distances = new Array();
  5670. this._tangents = new Array();
  5671. this._normals = new Array();
  5672. this._binormals = new Array();
  5673. for (var p = 0; p < path.length; p++) {
  5674. this._curve[p] = path[p].clone(); // hard copy
  5675. }
  5676. this._raw = raw || false;
  5677. this._compute(firstNormal);
  5678. }
  5679. /**
  5680. * Returns the Path3D array of successive Vector3 designing its curve.
  5681. */
  5682. Path3D.prototype.getCurve = function () {
  5683. return this._curve;
  5684. };
  5685. /**
  5686. * Returns an array populated with tangent vectors on each Path3D curve point.
  5687. */
  5688. Path3D.prototype.getTangents = function () {
  5689. return this._tangents;
  5690. };
  5691. /**
  5692. * Returns an array populated with normal vectors on each Path3D curve point.
  5693. */
  5694. Path3D.prototype.getNormals = function () {
  5695. return this._normals;
  5696. };
  5697. /**
  5698. * Returns an array populated with binormal vectors on each Path3D curve point.
  5699. */
  5700. Path3D.prototype.getBinormals = function () {
  5701. return this._binormals;
  5702. };
  5703. /**
  5704. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5705. */
  5706. Path3D.prototype.getDistances = function () {
  5707. return this._distances;
  5708. };
  5709. /**
  5710. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5711. * Returns the same object updated.
  5712. */
  5713. Path3D.prototype.update = function (path, firstNormal) {
  5714. if (firstNormal === void 0) { firstNormal = null; }
  5715. for (var p = 0; p < path.length; p++) {
  5716. this._curve[p].x = path[p].x;
  5717. this._curve[p].y = path[p].y;
  5718. this._curve[p].z = path[p].z;
  5719. }
  5720. this._compute(firstNormal);
  5721. return this;
  5722. };
  5723. // private function compute() : computes tangents, normals and binormals
  5724. Path3D.prototype._compute = function (firstNormal) {
  5725. var l = this._curve.length;
  5726. // first and last tangents
  5727. this._tangents[0] = this._getFirstNonNullVector(0);
  5728. if (!this._raw) {
  5729. this._tangents[0].normalize();
  5730. }
  5731. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5732. if (!this._raw) {
  5733. this._tangents[l - 1].normalize();
  5734. }
  5735. // normals and binormals at first point : arbitrary vector with _normalVector()
  5736. var tg0 = this._tangents[0];
  5737. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5738. this._normals[0] = pp0;
  5739. if (!this._raw) {
  5740. this._normals[0].normalize();
  5741. }
  5742. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5743. if (!this._raw) {
  5744. this._binormals[0].normalize();
  5745. }
  5746. this._distances[0] = 0.0;
  5747. // normals and binormals : next points
  5748. var prev; // previous vector (segment)
  5749. var cur; // current vector (segment)
  5750. var curTang; // current tangent
  5751. // previous normal
  5752. var prevBinor; // previous binormal
  5753. for (var i = 1; i < l; i++) {
  5754. // tangents
  5755. prev = this._getLastNonNullVector(i);
  5756. if (i < l - 1) {
  5757. cur = this._getFirstNonNullVector(i);
  5758. this._tangents[i] = prev.add(cur);
  5759. this._tangents[i].normalize();
  5760. }
  5761. this._distances[i] = this._distances[i - 1] + prev.length();
  5762. // normals and binormals
  5763. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5764. curTang = this._tangents[i];
  5765. prevBinor = this._binormals[i - 1];
  5766. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5767. if (!this._raw) {
  5768. this._normals[i].normalize();
  5769. }
  5770. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5771. if (!this._raw) {
  5772. this._binormals[i].normalize();
  5773. }
  5774. }
  5775. };
  5776. // private function getFirstNonNullVector(index)
  5777. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5778. Path3D.prototype._getFirstNonNullVector = function (index) {
  5779. var i = 1;
  5780. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5781. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5782. i++;
  5783. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5784. }
  5785. return nNVector;
  5786. };
  5787. // private function getLastNonNullVector(index)
  5788. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5789. Path3D.prototype._getLastNonNullVector = function (index) {
  5790. var i = 1;
  5791. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5792. while (nLVector.length() === 0 && index > i + 1) {
  5793. i++;
  5794. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5795. }
  5796. return nLVector;
  5797. };
  5798. // private function normalVector(v0, vt, va) :
  5799. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5800. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5801. Path3D.prototype._normalVector = function (v0, vt, va) {
  5802. var normal0;
  5803. var tgl = vt.length();
  5804. if (tgl === 0.0) {
  5805. tgl = 1.0;
  5806. }
  5807. if (va === undefined || va === null) {
  5808. var point;
  5809. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5810. point = new Vector3(0.0, -1.0, 0.0);
  5811. }
  5812. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5813. point = new Vector3(1.0, 0.0, 0.0);
  5814. }
  5815. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5816. point = new Vector3(0.0, 0.0, 1.0);
  5817. }
  5818. else {
  5819. point = Vector3.Zero();
  5820. }
  5821. normal0 = Vector3.Cross(vt, point);
  5822. }
  5823. else {
  5824. normal0 = Vector3.Cross(vt, va);
  5825. Vector3.CrossToRef(normal0, vt, normal0);
  5826. }
  5827. normal0.normalize();
  5828. return normal0;
  5829. };
  5830. return Path3D;
  5831. }());
  5832. BABYLON.Path3D = Path3D;
  5833. var Curve3 = /** @class */ (function () {
  5834. /**
  5835. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5836. * A Curve3 is designed from a series of successive Vector3.
  5837. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5838. */
  5839. function Curve3(points) {
  5840. this._length = 0.0;
  5841. this._points = points;
  5842. this._length = this._computeLength(points);
  5843. }
  5844. /**
  5845. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5846. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5847. * @param v1 (Vector3) the control point
  5848. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5849. * @param nbPoints (integer) the wanted number of points in the curve
  5850. */
  5851. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5852. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5853. var bez = new Array();
  5854. var equation = function (t, val0, val1, val2) {
  5855. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5856. return res;
  5857. };
  5858. for (var i = 0; i <= nbPoints; i++) {
  5859. 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)));
  5860. }
  5861. return new Curve3(bez);
  5862. };
  5863. /**
  5864. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5865. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5866. * @param v1 (Vector3) the first control point
  5867. * @param v2 (Vector3) the second control point
  5868. * @param v3 (Vector3) the end point of the Cubic Bezier
  5869. * @param nbPoints (integer) the wanted number of points in the curve
  5870. */
  5871. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5872. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5873. var bez = new Array();
  5874. var equation = function (t, val0, val1, val2, val3) {
  5875. 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;
  5876. return res;
  5877. };
  5878. for (var i = 0; i <= nbPoints; i++) {
  5879. 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)));
  5880. }
  5881. return new Curve3(bez);
  5882. };
  5883. /**
  5884. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5885. * @param p1 (Vector3) the origin point of the Hermite Spline
  5886. * @param t1 (Vector3) the tangent vector at the origin point
  5887. * @param p2 (Vector3) the end point of the Hermite Spline
  5888. * @param t2 (Vector3) the tangent vector at the end point
  5889. * @param nbPoints (integer) the wanted number of points in the curve
  5890. */
  5891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5892. var hermite = new Array();
  5893. var step = 1.0 / nbPoints;
  5894. for (var i = 0; i <= nbPoints; i++) {
  5895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5896. }
  5897. return new Curve3(hermite);
  5898. };
  5899. /**
  5900. * Returns a Curve3 object along a CatmullRom Spline curve :
  5901. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5902. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5903. */
  5904. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5905. var totalPoints = new Array();
  5906. totalPoints.push(points[0].clone());
  5907. Array.prototype.push.apply(totalPoints, points);
  5908. totalPoints.push(points[points.length - 1].clone());
  5909. var catmullRom = new Array();
  5910. var step = 1.0 / nbPoints;
  5911. var amount = 0.0;
  5912. for (var i = 0; i < totalPoints.length - 3; i++) {
  5913. amount = 0;
  5914. for (var c = 0; c < nbPoints; c++) {
  5915. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5916. amount += step;
  5917. }
  5918. }
  5919. i--;
  5920. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5921. return new Curve3(catmullRom);
  5922. };
  5923. /**
  5924. * Returns the Curve3 stored array of successive Vector3
  5925. */
  5926. Curve3.prototype.getPoints = function () {
  5927. return this._points;
  5928. };
  5929. /**
  5930. * Returns the computed length (float) of the curve.
  5931. */
  5932. Curve3.prototype.length = function () {
  5933. return this._length;
  5934. };
  5935. /**
  5936. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5937. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5938. * curveA and curveB keep unchanged.
  5939. */
  5940. Curve3.prototype.continue = function (curve) {
  5941. var lastPoint = this._points[this._points.length - 1];
  5942. var continuedPoints = this._points.slice();
  5943. var curvePoints = curve.getPoints();
  5944. for (var i = 1; i < curvePoints.length; i++) {
  5945. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5946. }
  5947. var continuedCurve = new Curve3(continuedPoints);
  5948. return continuedCurve;
  5949. };
  5950. Curve3.prototype._computeLength = function (path) {
  5951. var l = 0;
  5952. for (var i = 1; i < path.length; i++) {
  5953. l += (path[i].subtract(path[i - 1])).length();
  5954. }
  5955. return l;
  5956. };
  5957. return Curve3;
  5958. }());
  5959. BABYLON.Curve3 = Curve3;
  5960. // Vertex formats
  5961. var PositionNormalVertex = /** @class */ (function () {
  5962. function PositionNormalVertex(position, normal) {
  5963. if (position === void 0) { position = Vector3.Zero(); }
  5964. if (normal === void 0) { normal = Vector3.Up(); }
  5965. this.position = position;
  5966. this.normal = normal;
  5967. }
  5968. PositionNormalVertex.prototype.clone = function () {
  5969. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5970. };
  5971. return PositionNormalVertex;
  5972. }());
  5973. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5974. var PositionNormalTextureVertex = /** @class */ (function () {
  5975. function PositionNormalTextureVertex(position, normal, uv) {
  5976. if (position === void 0) { position = Vector3.Zero(); }
  5977. if (normal === void 0) { normal = Vector3.Up(); }
  5978. if (uv === void 0) { uv = Vector2.Zero(); }
  5979. this.position = position;
  5980. this.normal = normal;
  5981. this.uv = uv;
  5982. }
  5983. PositionNormalTextureVertex.prototype.clone = function () {
  5984. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5985. };
  5986. return PositionNormalTextureVertex;
  5987. }());
  5988. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5989. // Temporary pre-allocated objects for engine internal use
  5990. // usage in any internal function :
  5991. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5992. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5993. var Tmp = /** @class */ (function () {
  5994. function Tmp() {
  5995. }
  5996. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5997. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5998. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5999. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6000. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6001. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6002. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6003. Matrix.Zero(), Matrix.Zero(),
  6004. Matrix.Zero(), Matrix.Zero(),
  6005. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6006. return Tmp;
  6007. }());
  6008. BABYLON.Tmp = Tmp;
  6009. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6010. var MathTmp = /** @class */ (function () {
  6011. function MathTmp() {
  6012. }
  6013. MathTmp.Vector3 = [Vector3.Zero()];
  6014. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6015. MathTmp.Quaternion = [Quaternion.Zero()];
  6016. return MathTmp;
  6017. }());
  6018. })(BABYLON || (BABYLON = {}));
  6019. //# sourceMappingURL=babylon.math.js.map
  6020. var BABYLON;
  6021. (function (BABYLON) {
  6022. var Scalar = /** @class */ (function () {
  6023. function Scalar() {
  6024. }
  6025. /**
  6026. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6027. */
  6028. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6029. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6030. var num = a - b;
  6031. return -epsilon <= num && num <= epsilon;
  6032. };
  6033. /**
  6034. * Returns a string : the upper case translation of the number i to hexadecimal.
  6035. */
  6036. Scalar.ToHex = function (i) {
  6037. var str = i.toString(16);
  6038. if (i <= 15) {
  6039. return ("0" + str).toUpperCase();
  6040. }
  6041. return str.toUpperCase();
  6042. };
  6043. /**
  6044. * Returns -1 if value is negative and +1 is value is positive.
  6045. * Returns the value itself if it's equal to zero.
  6046. */
  6047. Scalar.Sign = function (value) {
  6048. value = +value; // convert to a number
  6049. if (value === 0 || isNaN(value))
  6050. return value;
  6051. return value > 0 ? 1 : -1;
  6052. };
  6053. /**
  6054. * Returns the value itself if it's between min and max.
  6055. * Returns min if the value is lower than min.
  6056. * Returns max if the value is greater than max.
  6057. */
  6058. Scalar.Clamp = function (value, min, max) {
  6059. if (min === void 0) { min = 0; }
  6060. if (max === void 0) { max = 1; }
  6061. return Math.min(max, Math.max(min, value));
  6062. };
  6063. /**
  6064. * Returns the log2 of value.
  6065. */
  6066. Scalar.Log2 = function (value) {
  6067. return Math.log(value) * Math.LOG2E;
  6068. };
  6069. /**
  6070. * Loops the value, so that it is never larger than length and never smaller than 0.
  6071. *
  6072. * This is similar to the modulo operator but it works with floating point numbers.
  6073. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6074. * With t = 5 and length = 2.5, the result would be 0.0.
  6075. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6076. */
  6077. Scalar.Repeat = function (value, length) {
  6078. return value - Math.floor(value / length) * length;
  6079. };
  6080. /**
  6081. * Normalize the value between 0.0 and 1.0 using min and max values
  6082. */
  6083. Scalar.Normalize = function (value, min, max) {
  6084. return (value - min) / (max - min);
  6085. };
  6086. /**
  6087. * Denormalize the value from 0.0 and 1.0 using min and max values
  6088. */
  6089. Scalar.Denormalize = function (normalized, min, max) {
  6090. return (normalized * (max - min) + min);
  6091. };
  6092. /**
  6093. * Calculates the shortest difference between two given angles given in degrees.
  6094. */
  6095. Scalar.DeltaAngle = function (current, target) {
  6096. var num = Scalar.Repeat(target - current, 360.0);
  6097. if (num > 180.0) {
  6098. num -= 360.0;
  6099. }
  6100. return num;
  6101. };
  6102. /**
  6103. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6104. *
  6105. * The returned value will move back and forth between 0 and length
  6106. */
  6107. Scalar.PingPong = function (tx, length) {
  6108. var t = Scalar.Repeat(tx, length * 2.0);
  6109. return length - Math.abs(t - length);
  6110. };
  6111. /**
  6112. * Interpolates between min and max with smoothing at the limits.
  6113. *
  6114. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6115. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6116. */
  6117. Scalar.SmoothStep = function (from, to, tx) {
  6118. var t = Scalar.Clamp(tx);
  6119. t = -2.0 * t * t * t + 3.0 * t * t;
  6120. return to * t + from * (1.0 - t);
  6121. };
  6122. /**
  6123. * Moves a value current towards target.
  6124. *
  6125. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6126. * Negative values of maxDelta pushes the value away from target.
  6127. */
  6128. Scalar.MoveTowards = function (current, target, maxDelta) {
  6129. var result = 0;
  6130. if (Math.abs(target - current) <= maxDelta) {
  6131. result = target;
  6132. }
  6133. else {
  6134. result = current + Scalar.Sign(target - current) * maxDelta;
  6135. }
  6136. return result;
  6137. };
  6138. /**
  6139. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6140. *
  6141. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6142. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6143. */
  6144. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6145. var num = Scalar.DeltaAngle(current, target);
  6146. var result = 0;
  6147. if (-maxDelta < num && num < maxDelta) {
  6148. result = target;
  6149. }
  6150. else {
  6151. target = current + num;
  6152. result = Scalar.MoveTowards(current, target, maxDelta);
  6153. }
  6154. return result;
  6155. };
  6156. /**
  6157. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6158. */
  6159. Scalar.Lerp = function (start, end, amount) {
  6160. return start + ((end - start) * amount);
  6161. };
  6162. /**
  6163. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6164. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6165. */
  6166. Scalar.LerpAngle = function (start, end, amount) {
  6167. var num = Scalar.Repeat(end - start, 360.0);
  6168. if (num > 180.0) {
  6169. num -= 360.0;
  6170. }
  6171. return start + num * Scalar.Clamp(amount);
  6172. };
  6173. /**
  6174. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6175. */
  6176. Scalar.InverseLerp = function (a, b, value) {
  6177. var result = 0;
  6178. if (a != b) {
  6179. result = Scalar.Clamp((value - a) / (b - a));
  6180. }
  6181. else {
  6182. result = 0.0;
  6183. }
  6184. return result;
  6185. };
  6186. /**
  6187. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6188. */
  6189. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6190. var squared = amount * amount;
  6191. var cubed = amount * squared;
  6192. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6193. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6194. var part3 = (cubed - (2.0 * squared)) + amount;
  6195. var part4 = cubed - squared;
  6196. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6197. };
  6198. /**
  6199. * Returns a random float number between and min and max values
  6200. */
  6201. Scalar.RandomRange = function (min, max) {
  6202. if (min === max)
  6203. return min;
  6204. return ((Math.random() * (max - min)) + min);
  6205. };
  6206. /**
  6207. * This function returns percentage of a number in a given range.
  6208. *
  6209. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6210. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6211. */
  6212. Scalar.RangeToPercent = function (number, min, max) {
  6213. return ((number - min) / (max - min));
  6214. };
  6215. /**
  6216. * This function returns number that corresponds to the percentage in a given range.
  6217. *
  6218. * PercentToRange(0.34,0,100) will return 34.
  6219. */
  6220. Scalar.PercentToRange = function (percent, min, max) {
  6221. return ((max - min) * percent + min);
  6222. };
  6223. /**
  6224. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6225. * @param angle The angle to normalize in radian.
  6226. * @return The converted angle.
  6227. */
  6228. Scalar.NormalizeRadians = function (angle) {
  6229. // More precise but slower version kept for reference.
  6230. // angle = angle % Tools.TwoPi;
  6231. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6232. //if (angle > Math.PI) {
  6233. // angle -= Tools.TwoPi;
  6234. //}
  6235. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6236. return angle;
  6237. };
  6238. /**
  6239. * Two pi constants convenient for computation.
  6240. */
  6241. Scalar.TwoPi = Math.PI * 2;
  6242. return Scalar;
  6243. }());
  6244. BABYLON.Scalar = Scalar;
  6245. })(BABYLON || (BABYLON = {}));
  6246. //# sourceMappingURL=babylon.math.scalar.js.map
  6247. //# sourceMappingURL=babylon.mixins.js.map
  6248. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6249. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6250. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6251. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6252. //# sourceMappingURL=babylon.webgl2.js.map
  6253. var BABYLON;
  6254. (function (BABYLON) {
  6255. var __decoratorInitialStore = {};
  6256. var __mergedStore = {};
  6257. var _copySource = function (creationFunction, source, instanciate) {
  6258. var destination = creationFunction();
  6259. // Tags
  6260. if (BABYLON.Tags) {
  6261. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6262. }
  6263. var classStore = getMergedStore(destination);
  6264. // Properties
  6265. for (var property in classStore) {
  6266. var propertyDescriptor = classStore[property];
  6267. var sourceProperty = source[property];
  6268. var propertyType = propertyDescriptor.type;
  6269. if (sourceProperty !== undefined && sourceProperty !== null) {
  6270. switch (propertyType) {
  6271. case 0: // Value
  6272. case 6:// Mesh reference
  6273. destination[property] = sourceProperty;
  6274. break;
  6275. case 1:// Texture
  6276. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6277. break;
  6278. case 2: // Color3
  6279. case 3: // FresnelParameters
  6280. case 4: // Vector2
  6281. case 5: // Vector3
  6282. case 7: // Color Curves
  6283. case 10:// Quaternion
  6284. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6285. break;
  6286. }
  6287. }
  6288. }
  6289. return destination;
  6290. };
  6291. function getDirectStore(target) {
  6292. var classKey = target.getClassName();
  6293. if (!__decoratorInitialStore[classKey]) {
  6294. __decoratorInitialStore[classKey] = {};
  6295. }
  6296. return __decoratorInitialStore[classKey];
  6297. }
  6298. /**
  6299. * Return the list of properties flagged as serializable
  6300. * @param target: host object
  6301. */
  6302. function getMergedStore(target) {
  6303. var classKey = target.getClassName();
  6304. if (__mergedStore[classKey]) {
  6305. return __mergedStore[classKey];
  6306. }
  6307. __mergedStore[classKey] = {};
  6308. var store = __mergedStore[classKey];
  6309. var currentTarget = target;
  6310. var currentKey = classKey;
  6311. while (currentKey) {
  6312. var initialStore = __decoratorInitialStore[currentKey];
  6313. for (var property in initialStore) {
  6314. store[property] = initialStore[property];
  6315. }
  6316. var parent_1 = void 0;
  6317. var done = false;
  6318. do {
  6319. parent_1 = Object.getPrototypeOf(currentTarget);
  6320. if (!parent_1.getClassName) {
  6321. done = true;
  6322. break;
  6323. }
  6324. if (parent_1.getClassName() !== currentKey) {
  6325. break;
  6326. }
  6327. currentTarget = parent_1;
  6328. } while (parent_1);
  6329. if (done) {
  6330. break;
  6331. }
  6332. currentKey = parent_1.getClassName();
  6333. currentTarget = parent_1;
  6334. }
  6335. return store;
  6336. }
  6337. function generateSerializableMember(type, sourceName) {
  6338. return function (target, propertyKey) {
  6339. var classStore = getDirectStore(target);
  6340. if (!classStore[propertyKey]) {
  6341. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6342. }
  6343. };
  6344. }
  6345. function generateExpandMember(setCallback, targetKey) {
  6346. if (targetKey === void 0) { targetKey = null; }
  6347. return function (target, propertyKey) {
  6348. var key = targetKey || ("_" + propertyKey);
  6349. Object.defineProperty(target, propertyKey, {
  6350. get: function () {
  6351. return this[key];
  6352. },
  6353. set: function (value) {
  6354. if (this[key] === value) {
  6355. return;
  6356. }
  6357. this[key] = value;
  6358. target[setCallback].apply(this);
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. };
  6364. }
  6365. function expandToProperty(callback, targetKey) {
  6366. if (targetKey === void 0) { targetKey = null; }
  6367. return generateExpandMember(callback, targetKey);
  6368. }
  6369. BABYLON.expandToProperty = expandToProperty;
  6370. function serialize(sourceName) {
  6371. return generateSerializableMember(0, sourceName); // value member
  6372. }
  6373. BABYLON.serialize = serialize;
  6374. function serializeAsTexture(sourceName) {
  6375. return generateSerializableMember(1, sourceName); // texture member
  6376. }
  6377. BABYLON.serializeAsTexture = serializeAsTexture;
  6378. function serializeAsColor3(sourceName) {
  6379. return generateSerializableMember(2, sourceName); // color3 member
  6380. }
  6381. BABYLON.serializeAsColor3 = serializeAsColor3;
  6382. function serializeAsFresnelParameters(sourceName) {
  6383. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6384. }
  6385. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6386. function serializeAsVector2(sourceName) {
  6387. return generateSerializableMember(4, sourceName); // vector2 member
  6388. }
  6389. BABYLON.serializeAsVector2 = serializeAsVector2;
  6390. function serializeAsVector3(sourceName) {
  6391. return generateSerializableMember(5, sourceName); // vector3 member
  6392. }
  6393. BABYLON.serializeAsVector3 = serializeAsVector3;
  6394. function serializeAsMeshReference(sourceName) {
  6395. return generateSerializableMember(6, sourceName); // mesh reference member
  6396. }
  6397. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6398. function serializeAsColorCurves(sourceName) {
  6399. return generateSerializableMember(7, sourceName); // color curves
  6400. }
  6401. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6402. function serializeAsColor4(sourceName) {
  6403. return generateSerializableMember(8, sourceName); // color 4
  6404. }
  6405. BABYLON.serializeAsColor4 = serializeAsColor4;
  6406. function serializeAsImageProcessingConfiguration(sourceName) {
  6407. return generateSerializableMember(9, sourceName); // image processing
  6408. }
  6409. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6410. function serializeAsQuaternion(sourceName) {
  6411. return generateSerializableMember(10, sourceName); // quaternion member
  6412. }
  6413. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6414. var SerializationHelper = /** @class */ (function () {
  6415. function SerializationHelper() {
  6416. }
  6417. SerializationHelper.Serialize = function (entity, serializationObject) {
  6418. if (!serializationObject) {
  6419. serializationObject = {};
  6420. }
  6421. // Tags
  6422. if (BABYLON.Tags) {
  6423. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6424. }
  6425. var serializedProperties = getMergedStore(entity);
  6426. // Properties
  6427. for (var property in serializedProperties) {
  6428. var propertyDescriptor = serializedProperties[property];
  6429. var targetPropertyName = propertyDescriptor.sourceName || property;
  6430. var propertyType = propertyDescriptor.type;
  6431. var sourceProperty = entity[property];
  6432. if (sourceProperty !== undefined && sourceProperty !== null) {
  6433. switch (propertyType) {
  6434. case 0:// Value
  6435. serializationObject[targetPropertyName] = sourceProperty;
  6436. break;
  6437. case 1:// Texture
  6438. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6439. break;
  6440. case 2:// Color3
  6441. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6442. break;
  6443. case 3:// FresnelParameters
  6444. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6445. break;
  6446. case 4:// Vector2
  6447. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6448. break;
  6449. case 5:// Vector3
  6450. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6451. break;
  6452. case 6:// Mesh reference
  6453. serializationObject[targetPropertyName] = sourceProperty.id;
  6454. break;
  6455. case 7:// Color Curves
  6456. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6457. break;
  6458. case 8:// Color 4
  6459. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6460. break;
  6461. case 9:// Image Processing
  6462. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6463. break;
  6464. }
  6465. }
  6466. }
  6467. return serializationObject;
  6468. };
  6469. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6470. if (rootUrl === void 0) { rootUrl = null; }
  6471. var destination = creationFunction();
  6472. if (!rootUrl) {
  6473. rootUrl = "";
  6474. }
  6475. // Tags
  6476. if (BABYLON.Tags) {
  6477. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6478. }
  6479. var classStore = getMergedStore(destination);
  6480. // Properties
  6481. for (var property in classStore) {
  6482. var propertyDescriptor = classStore[property];
  6483. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6484. var propertyType = propertyDescriptor.type;
  6485. if (sourceProperty !== undefined && sourceProperty !== null) {
  6486. var dest = destination;
  6487. switch (propertyType) {
  6488. case 0:// Value
  6489. dest[property] = sourceProperty;
  6490. break;
  6491. case 1:// Texture
  6492. if (scene) {
  6493. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6494. }
  6495. break;
  6496. case 2:// Color3
  6497. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6498. break;
  6499. case 3:// FresnelParameters
  6500. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6501. break;
  6502. case 4:// Vector2
  6503. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6504. break;
  6505. case 5:// Vector3
  6506. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6507. break;
  6508. case 6:// Mesh reference
  6509. if (scene) {
  6510. dest[property] = scene.getLastMeshByID(sourceProperty);
  6511. }
  6512. break;
  6513. case 7:// Color Curves
  6514. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6515. break;
  6516. case 8:// Color 4
  6517. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6518. break;
  6519. case 9:// Image Processing
  6520. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6521. break;
  6522. }
  6523. }
  6524. }
  6525. return destination;
  6526. };
  6527. SerializationHelper.Clone = function (creationFunction, source) {
  6528. return _copySource(creationFunction, source, false);
  6529. };
  6530. SerializationHelper.Instanciate = function (creationFunction, source) {
  6531. return _copySource(creationFunction, source, true);
  6532. };
  6533. return SerializationHelper;
  6534. }());
  6535. BABYLON.SerializationHelper = SerializationHelper;
  6536. })(BABYLON || (BABYLON = {}));
  6537. //# sourceMappingURL=babylon.decorators.js.map
  6538. var BABYLON;
  6539. (function (BABYLON) {
  6540. /**
  6541. * A class serves as a medium between the observable and its observers
  6542. */
  6543. var EventState = /** @class */ (function () {
  6544. /**
  6545. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6546. */
  6547. function EventState(mask, skipNextObservers, target, currentTarget) {
  6548. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6549. this.initalize(mask, skipNextObservers, target, currentTarget);
  6550. }
  6551. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6552. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6553. this.mask = mask;
  6554. this.skipNextObservers = skipNextObservers;
  6555. this.target = target;
  6556. this.currentTarget = currentTarget;
  6557. return this;
  6558. };
  6559. return EventState;
  6560. }());
  6561. BABYLON.EventState = EventState;
  6562. /**
  6563. * Represent an Observer registered to a given Observable object.
  6564. */
  6565. var Observer = /** @class */ (function () {
  6566. function Observer(callback, mask, scope) {
  6567. if (scope === void 0) { scope = null; }
  6568. this.callback = callback;
  6569. this.mask = mask;
  6570. this.scope = scope;
  6571. }
  6572. return Observer;
  6573. }());
  6574. BABYLON.Observer = Observer;
  6575. /**
  6576. * Represent a list of observers registered to multiple Observables object.
  6577. */
  6578. var MultiObserver = /** @class */ (function () {
  6579. function MultiObserver() {
  6580. }
  6581. MultiObserver.prototype.dispose = function () {
  6582. if (this._observers && this._observables) {
  6583. for (var index = 0; index < this._observers.length; index++) {
  6584. this._observables[index].remove(this._observers[index]);
  6585. }
  6586. }
  6587. this._observers = null;
  6588. this._observables = null;
  6589. };
  6590. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6591. if (mask === void 0) { mask = -1; }
  6592. if (scope === void 0) { scope = null; }
  6593. var result = new MultiObserver();
  6594. result._observers = new Array();
  6595. result._observables = observables;
  6596. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6597. var observable = observables_1[_i];
  6598. var observer = observable.add(callback, mask, false, scope);
  6599. if (observer) {
  6600. result._observers.push(observer);
  6601. }
  6602. }
  6603. return result;
  6604. };
  6605. return MultiObserver;
  6606. }());
  6607. BABYLON.MultiObserver = MultiObserver;
  6608. /**
  6609. * The Observable class is a simple implementation of the Observable pattern.
  6610. * 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.
  6611. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6612. * 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).
  6613. * 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.
  6614. */
  6615. var Observable = /** @class */ (function () {
  6616. function Observable(onObserverAdded) {
  6617. this._observers = new Array();
  6618. this._eventState = new EventState(0);
  6619. if (onObserverAdded) {
  6620. this._onObserverAdded = onObserverAdded;
  6621. }
  6622. }
  6623. /**
  6624. * Create a new Observer with the specified callback
  6625. * @param callback the callback that will be executed for that Observer
  6626. * @param mask the mask used to filter observers
  6627. * @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.
  6628. * @param scope optional scope for the callback to be called from
  6629. */
  6630. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6631. if (mask === void 0) { mask = -1; }
  6632. if (insertFirst === void 0) { insertFirst = false; }
  6633. if (scope === void 0) { scope = null; }
  6634. if (!callback) {
  6635. return null;
  6636. }
  6637. var observer = new Observer(callback, mask, scope);
  6638. if (insertFirst) {
  6639. this._observers.unshift(observer);
  6640. }
  6641. else {
  6642. this._observers.push(observer);
  6643. }
  6644. if (this._onObserverAdded) {
  6645. this._onObserverAdded(observer);
  6646. }
  6647. return observer;
  6648. };
  6649. /**
  6650. * Remove an Observer from the Observable object
  6651. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6652. */
  6653. Observable.prototype.remove = function (observer) {
  6654. if (!observer) {
  6655. return false;
  6656. }
  6657. var index = this._observers.indexOf(observer);
  6658. if (index !== -1) {
  6659. this._observers.splice(index, 1);
  6660. return true;
  6661. }
  6662. return false;
  6663. };
  6664. /**
  6665. * Remove a callback from the Observable object
  6666. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6667. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6668. */
  6669. Observable.prototype.removeCallback = function (callback, scope) {
  6670. for (var index = 0; index < this._observers.length; index++) {
  6671. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6672. this._observers.splice(index, 1);
  6673. return true;
  6674. }
  6675. }
  6676. return false;
  6677. };
  6678. /**
  6679. * Notify all Observers by calling their respective callback with the given data
  6680. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6681. * @param eventData
  6682. * @param mask
  6683. */
  6684. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6685. if (mask === void 0) { mask = -1; }
  6686. if (!this._observers.length) {
  6687. return true;
  6688. }
  6689. var state = this._eventState;
  6690. state.mask = mask;
  6691. state.target = target;
  6692. state.currentTarget = currentTarget;
  6693. state.skipNextObservers = false;
  6694. state.lastReturnValue = eventData;
  6695. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6696. var obs = _a[_i];
  6697. if (obs.mask & mask) {
  6698. if (obs.scope) {
  6699. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  6700. }
  6701. else {
  6702. state.lastReturnValue = obs.callback(eventData, state);
  6703. }
  6704. }
  6705. if (state.skipNextObservers) {
  6706. return false;
  6707. }
  6708. }
  6709. return true;
  6710. };
  6711. /**
  6712. * Calling this will execute each callback, expecting it to be a promise or return a value.
  6713. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  6714. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  6715. * and it is crucial that all callbacks will be executed.
  6716. * The order of the callbacks is kept, callbacks are not executed parallel.
  6717. *
  6718. * @param eventData The data to be sent to each callback
  6719. * @param mask is used to filter observers defaults to -1
  6720. * @param target the callback target (see EventState)
  6721. * @param currentTarget The current object in the bubbling phase
  6722. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  6723. */
  6724. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  6725. if (mask === void 0) { mask = -1; }
  6726. // create an empty promise
  6727. var p = Promise.resolve(eventData);
  6728. // no observers? return this promise.
  6729. if (!this._observers.length) {
  6730. return p;
  6731. }
  6732. var state = this._eventState;
  6733. state.mask = mask;
  6734. state.target = target;
  6735. state.currentTarget = currentTarget;
  6736. state.skipNextObservers = false;
  6737. // execute one callback after another (not using Promise.all, the order is important)
  6738. this._observers.forEach(function (obs) {
  6739. if (state.skipNextObservers) {
  6740. return;
  6741. }
  6742. if (obs.mask & mask) {
  6743. if (obs.scope) {
  6744. p = p.then(function (lastReturnedValue) {
  6745. state.lastReturnValue = lastReturnedValue;
  6746. return obs.callback.apply(obs.scope, [eventData, state]);
  6747. });
  6748. }
  6749. else {
  6750. p = p.then(function (lastReturnedValue) {
  6751. state.lastReturnValue = lastReturnedValue;
  6752. return obs.callback(eventData, state);
  6753. });
  6754. }
  6755. }
  6756. });
  6757. // return the eventData
  6758. return p.then(function () { return eventData; });
  6759. };
  6760. /**
  6761. * Notify a specific observer
  6762. * @param eventData
  6763. * @param mask
  6764. */
  6765. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6766. if (mask === void 0) { mask = -1; }
  6767. var state = this._eventState;
  6768. state.mask = mask;
  6769. state.skipNextObservers = false;
  6770. observer.callback(eventData, state);
  6771. };
  6772. /**
  6773. * return true is the Observable has at least one Observer registered
  6774. */
  6775. Observable.prototype.hasObservers = function () {
  6776. return this._observers.length > 0;
  6777. };
  6778. /**
  6779. * Clear the list of observers
  6780. */
  6781. Observable.prototype.clear = function () {
  6782. this._observers = new Array();
  6783. this._onObserverAdded = null;
  6784. };
  6785. /**
  6786. * Clone the current observable
  6787. */
  6788. Observable.prototype.clone = function () {
  6789. var result = new Observable();
  6790. result._observers = this._observers.slice(0);
  6791. return result;
  6792. };
  6793. /**
  6794. * Does this observable handles observer registered with a given mask
  6795. * @param {number} trigger - the mask to be tested
  6796. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6797. **/
  6798. Observable.prototype.hasSpecificMask = function (mask) {
  6799. if (mask === void 0) { mask = -1; }
  6800. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6801. var obs = _a[_i];
  6802. if (obs.mask & mask || obs.mask === mask) {
  6803. return true;
  6804. }
  6805. }
  6806. return false;
  6807. };
  6808. return Observable;
  6809. }());
  6810. BABYLON.Observable = Observable;
  6811. })(BABYLON || (BABYLON = {}));
  6812. //# sourceMappingURL=babylon.observable.js.map
  6813. var BABYLON;
  6814. (function (BABYLON) {
  6815. var SmartArray = /** @class */ (function () {
  6816. function SmartArray(capacity) {
  6817. this.length = 0;
  6818. this.data = new Array(capacity);
  6819. this._id = SmartArray._GlobalId++;
  6820. }
  6821. SmartArray.prototype.push = function (value) {
  6822. this.data[this.length++] = value;
  6823. if (this.length > this.data.length) {
  6824. this.data.length *= 2;
  6825. }
  6826. };
  6827. SmartArray.prototype.forEach = function (func) {
  6828. for (var index = 0; index < this.length; index++) {
  6829. func(this.data[index]);
  6830. }
  6831. };
  6832. SmartArray.prototype.sort = function (compareFn) {
  6833. this.data.sort(compareFn);
  6834. };
  6835. SmartArray.prototype.reset = function () {
  6836. this.length = 0;
  6837. };
  6838. SmartArray.prototype.dispose = function () {
  6839. this.reset();
  6840. if (this.data) {
  6841. this.data.length = 0;
  6842. this.data = [];
  6843. }
  6844. };
  6845. SmartArray.prototype.concat = function (array) {
  6846. if (array.length === 0) {
  6847. return;
  6848. }
  6849. if (this.length + array.length > this.data.length) {
  6850. this.data.length = (this.length + array.length) * 2;
  6851. }
  6852. for (var index = 0; index < array.length; index++) {
  6853. this.data[this.length++] = (array.data || array)[index];
  6854. }
  6855. };
  6856. SmartArray.prototype.indexOf = function (value) {
  6857. var position = this.data.indexOf(value);
  6858. if (position >= this.length) {
  6859. return -1;
  6860. }
  6861. return position;
  6862. };
  6863. SmartArray.prototype.contains = function (value) {
  6864. return this.data.indexOf(value) !== -1;
  6865. };
  6866. // Statics
  6867. SmartArray._GlobalId = 0;
  6868. return SmartArray;
  6869. }());
  6870. BABYLON.SmartArray = SmartArray;
  6871. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6872. __extends(SmartArrayNoDuplicate, _super);
  6873. function SmartArrayNoDuplicate() {
  6874. var _this = _super !== null && _super.apply(this, arguments) || this;
  6875. _this._duplicateId = 0;
  6876. return _this;
  6877. }
  6878. SmartArrayNoDuplicate.prototype.push = function (value) {
  6879. _super.prototype.push.call(this, value);
  6880. if (!value.__smartArrayFlags) {
  6881. value.__smartArrayFlags = {};
  6882. }
  6883. value.__smartArrayFlags[this._id] = this._duplicateId;
  6884. };
  6885. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6886. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6887. return false;
  6888. }
  6889. this.push(value);
  6890. return true;
  6891. };
  6892. SmartArrayNoDuplicate.prototype.reset = function () {
  6893. _super.prototype.reset.call(this);
  6894. this._duplicateId++;
  6895. };
  6896. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6897. if (array.length === 0) {
  6898. return;
  6899. }
  6900. if (this.length + array.length > this.data.length) {
  6901. this.data.length = (this.length + array.length) * 2;
  6902. }
  6903. for (var index = 0; index < array.length; index++) {
  6904. var item = (array.data || array)[index];
  6905. this.pushNoDuplicate(item);
  6906. }
  6907. };
  6908. return SmartArrayNoDuplicate;
  6909. }(SmartArray));
  6910. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6911. })(BABYLON || (BABYLON = {}));
  6912. //# sourceMappingURL=babylon.smartArray.js.map
  6913. var BABYLON;
  6914. (function (BABYLON) {
  6915. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6916. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6917. var LoadFileError = /** @class */ (function (_super) {
  6918. __extends(LoadFileError, _super);
  6919. function LoadFileError(message, request) {
  6920. var _this = _super.call(this, message) || this;
  6921. _this.request = request;
  6922. _this.name = "LoadFileError";
  6923. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6924. return _this;
  6925. }
  6926. // Polyfill for Object.setPrototypeOf if necessary.
  6927. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6928. return LoadFileError;
  6929. }(Error));
  6930. BABYLON.LoadFileError = LoadFileError;
  6931. var RetryStrategy = /** @class */ (function () {
  6932. function RetryStrategy() {
  6933. }
  6934. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6935. if (maxRetries === void 0) { maxRetries = 3; }
  6936. if (baseInterval === void 0) { baseInterval = 500; }
  6937. return function (url, request, retryIndex) {
  6938. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6939. return -1;
  6940. }
  6941. return Math.pow(2, retryIndex) * baseInterval;
  6942. };
  6943. };
  6944. return RetryStrategy;
  6945. }());
  6946. BABYLON.RetryStrategy = RetryStrategy;
  6947. // Screenshots
  6948. var screenshotCanvas;
  6949. var cloneValue = function (source, destinationObject) {
  6950. if (!source)
  6951. return null;
  6952. if (source instanceof BABYLON.Mesh) {
  6953. return null;
  6954. }
  6955. if (source instanceof BABYLON.SubMesh) {
  6956. return source.clone(destinationObject);
  6957. }
  6958. else if (source.clone) {
  6959. return source.clone();
  6960. }
  6961. return null;
  6962. };
  6963. var Tools = /** @class */ (function () {
  6964. function Tools() {
  6965. }
  6966. /**
  6967. * Interpolates between a and b via alpha
  6968. * @param a The lower value (returned when alpha = 0)
  6969. * @param b The upper value (returned when alpha = 1)
  6970. * @param alpha The interpolation-factor
  6971. * @return The mixed value
  6972. */
  6973. Tools.Mix = function (a, b, alpha) {
  6974. return a * (1 - alpha) + b * alpha;
  6975. };
  6976. Tools.Instantiate = function (className) {
  6977. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6978. return Tools.RegisteredExternalClasses[className];
  6979. }
  6980. var arr = className.split(".");
  6981. var fn = (window || this);
  6982. for (var i = 0, len = arr.length; i < len; i++) {
  6983. fn = fn[arr[i]];
  6984. }
  6985. if (typeof fn !== "function") {
  6986. return null;
  6987. }
  6988. return fn;
  6989. };
  6990. /**
  6991. * Provides a slice function that will work even on IE
  6992. * @param data defines the array to slice
  6993. * @returns the new sliced array
  6994. */
  6995. Tools.Slice = function (data) {
  6996. if (data.slice) {
  6997. return data.slice();
  6998. }
  6999. return Array.prototype.slice.call(data);
  7000. };
  7001. Tools.SetImmediate = function (action) {
  7002. if (window.setImmediate) {
  7003. window.setImmediate(action);
  7004. }
  7005. else {
  7006. setTimeout(action, 1);
  7007. }
  7008. };
  7009. Tools.IsExponentOfTwo = function (value) {
  7010. var count = 1;
  7011. do {
  7012. count *= 2;
  7013. } while (count < value);
  7014. return count === value;
  7015. };
  7016. /**
  7017. * Find the next highest power of two.
  7018. * @param x Number to start search from.
  7019. * @return Next highest power of two.
  7020. */
  7021. Tools.CeilingPOT = function (x) {
  7022. x--;
  7023. x |= x >> 1;
  7024. x |= x >> 2;
  7025. x |= x >> 4;
  7026. x |= x >> 8;
  7027. x |= x >> 16;
  7028. x++;
  7029. return x;
  7030. };
  7031. /**
  7032. * Find the next lowest power of two.
  7033. * @param x Number to start search from.
  7034. * @return Next lowest power of two.
  7035. */
  7036. Tools.FloorPOT = function (x) {
  7037. x = x | (x >> 1);
  7038. x = x | (x >> 2);
  7039. x = x | (x >> 4);
  7040. x = x | (x >> 8);
  7041. x = x | (x >> 16);
  7042. return x - (x >> 1);
  7043. };
  7044. /**
  7045. * Find the nearest power of two.
  7046. * @param x Number to start search from.
  7047. * @return Next nearest power of two.
  7048. */
  7049. Tools.NearestPOT = function (x) {
  7050. var c = Tools.CeilingPOT(x);
  7051. var f = Tools.FloorPOT(x);
  7052. return (c - x) > (x - f) ? f : c;
  7053. };
  7054. Tools.GetExponentOfTwo = function (value, max, mode) {
  7055. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7056. var pot;
  7057. switch (mode) {
  7058. case BABYLON.Engine.SCALEMODE_FLOOR:
  7059. pot = Tools.FloorPOT(value);
  7060. break;
  7061. case BABYLON.Engine.SCALEMODE_NEAREST:
  7062. pot = Tools.NearestPOT(value);
  7063. break;
  7064. case BABYLON.Engine.SCALEMODE_CEILING:
  7065. default:
  7066. pot = Tools.CeilingPOT(value);
  7067. break;
  7068. }
  7069. return Math.min(pot, max);
  7070. };
  7071. Tools.GetFilename = function (path) {
  7072. var index = path.lastIndexOf("/");
  7073. if (index < 0)
  7074. return path;
  7075. return path.substring(index + 1);
  7076. };
  7077. Tools.GetFolderPath = function (uri) {
  7078. var index = uri.lastIndexOf("/");
  7079. if (index < 0)
  7080. return "";
  7081. return uri.substring(0, index + 1);
  7082. };
  7083. Tools.GetDOMTextContent = function (element) {
  7084. var result = "";
  7085. var child = element.firstChild;
  7086. while (child) {
  7087. if (child.nodeType === 3) {
  7088. result += child.textContent;
  7089. }
  7090. child = child.nextSibling;
  7091. }
  7092. return result;
  7093. };
  7094. Tools.ToDegrees = function (angle) {
  7095. return angle * 180 / Math.PI;
  7096. };
  7097. Tools.ToRadians = function (angle) {
  7098. return angle * Math.PI / 180;
  7099. };
  7100. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7101. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7102. var output = "";
  7103. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7104. var i = 0;
  7105. var bytes = new Uint8Array(buffer);
  7106. while (i < bytes.length) {
  7107. chr1 = bytes[i++];
  7108. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7109. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7110. enc1 = chr1 >> 2;
  7111. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7112. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7113. enc4 = chr3 & 63;
  7114. if (isNaN(chr2)) {
  7115. enc3 = enc4 = 64;
  7116. }
  7117. else if (isNaN(chr3)) {
  7118. enc4 = 64;
  7119. }
  7120. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7121. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7122. }
  7123. return "data:image/png;base64," + output;
  7124. };
  7125. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7126. if (bias === void 0) { bias = null; }
  7127. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7128. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7129. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7130. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7131. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7132. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7133. }
  7134. if (bias) {
  7135. minimum.x -= minimum.x * bias.x + bias.y;
  7136. minimum.y -= minimum.y * bias.x + bias.y;
  7137. minimum.z -= minimum.z * bias.x + bias.y;
  7138. maximum.x += maximum.x * bias.x + bias.y;
  7139. maximum.y += maximum.y * bias.x + bias.y;
  7140. maximum.z += maximum.z * bias.x + bias.y;
  7141. }
  7142. return {
  7143. minimum: minimum,
  7144. maximum: maximum
  7145. };
  7146. };
  7147. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7148. if (bias === void 0) { bias = null; }
  7149. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7150. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7151. if (!stride) {
  7152. stride = 3;
  7153. }
  7154. for (var index = start; index < start + count; index++) {
  7155. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7156. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7157. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7158. }
  7159. if (bias) {
  7160. minimum.x -= minimum.x * bias.x + bias.y;
  7161. minimum.y -= minimum.y * bias.x + bias.y;
  7162. minimum.z -= minimum.z * bias.x + bias.y;
  7163. maximum.x += maximum.x * bias.x + bias.y;
  7164. maximum.y += maximum.y * bias.x + bias.y;
  7165. maximum.z += maximum.z * bias.x + bias.y;
  7166. }
  7167. return {
  7168. minimum: minimum,
  7169. maximum: maximum
  7170. };
  7171. };
  7172. Tools.Vector2ArrayFeeder = function (array) {
  7173. return function (index) {
  7174. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7175. var length = isFloatArray ? array.length / 2 : array.length;
  7176. if (index >= length) {
  7177. return null;
  7178. }
  7179. if (isFloatArray) {
  7180. var fa = array;
  7181. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7182. }
  7183. var a = array;
  7184. return a[index];
  7185. };
  7186. };
  7187. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7188. if (bias === void 0) { bias = null; }
  7189. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7190. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7191. var i = 0;
  7192. var cur = feeder(i++);
  7193. while (cur) {
  7194. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7195. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7196. cur = feeder(i++);
  7197. }
  7198. if (bias) {
  7199. minimum.x -= minimum.x * bias.x + bias.y;
  7200. minimum.y -= minimum.y * bias.x + bias.y;
  7201. maximum.x += maximum.x * bias.x + bias.y;
  7202. maximum.y += maximum.y * bias.x + bias.y;
  7203. }
  7204. return {
  7205. minimum: minimum,
  7206. maximum: maximum
  7207. };
  7208. };
  7209. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7210. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7211. return null;
  7212. return Array.isArray(obj) ? obj : [obj];
  7213. };
  7214. // Misc.
  7215. Tools.GetPointerPrefix = function () {
  7216. var eventPrefix = "pointer";
  7217. // Check if pointer events are supported
  7218. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7219. eventPrefix = "mouse";
  7220. }
  7221. return eventPrefix;
  7222. };
  7223. /**
  7224. * @param func - the function to be called
  7225. * @param requester - the object that will request the next frame. Falls back to window.
  7226. */
  7227. Tools.QueueNewFrame = function (func, requester) {
  7228. if (!Tools.IsWindowObjectExist()) {
  7229. return setTimeout(func, 16);
  7230. }
  7231. if (!requester) {
  7232. requester = window;
  7233. }
  7234. if (requester.requestAnimationFrame) {
  7235. return requester.requestAnimationFrame(func);
  7236. }
  7237. else if (requester.msRequestAnimationFrame) {
  7238. return requester.msRequestAnimationFrame(func);
  7239. }
  7240. else if (requester.webkitRequestAnimationFrame) {
  7241. return requester.webkitRequestAnimationFrame(func);
  7242. }
  7243. else if (requester.mozRequestAnimationFrame) {
  7244. return requester.mozRequestAnimationFrame(func);
  7245. }
  7246. else if (requester.oRequestAnimationFrame) {
  7247. return requester.oRequestAnimationFrame(func);
  7248. }
  7249. else {
  7250. return window.setTimeout(func, 16);
  7251. }
  7252. };
  7253. Tools.RequestFullscreen = function (element) {
  7254. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7255. if (!requestFunction)
  7256. return;
  7257. requestFunction.call(element);
  7258. };
  7259. Tools.ExitFullscreen = function () {
  7260. if (document.exitFullscreen) {
  7261. document.exitFullscreen();
  7262. }
  7263. else if (document.mozCancelFullScreen) {
  7264. document.mozCancelFullScreen();
  7265. }
  7266. else if (document.webkitCancelFullScreen) {
  7267. document.webkitCancelFullScreen();
  7268. }
  7269. else if (document.msCancelFullScreen) {
  7270. document.msCancelFullScreen();
  7271. }
  7272. };
  7273. Tools.SetCorsBehavior = function (url, element) {
  7274. if (url && url.indexOf("data:") === 0) {
  7275. return;
  7276. }
  7277. if (Tools.CorsBehavior) {
  7278. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7279. element.crossOrigin = Tools.CorsBehavior;
  7280. }
  7281. else {
  7282. var result = Tools.CorsBehavior(url);
  7283. if (result) {
  7284. element.crossOrigin = result;
  7285. }
  7286. }
  7287. }
  7288. };
  7289. // External files
  7290. Tools.CleanUrl = function (url) {
  7291. url = url.replace(/#/mg, "%23");
  7292. return url;
  7293. };
  7294. Tools.LoadImage = function (url, onLoad, onError, database) {
  7295. if (url instanceof ArrayBuffer) {
  7296. url = Tools.EncodeArrayBufferTobase64(url);
  7297. }
  7298. url = Tools.CleanUrl(url);
  7299. url = Tools.PreprocessUrl(url);
  7300. var img = new Image();
  7301. Tools.SetCorsBehavior(url, img);
  7302. img.onload = function () {
  7303. onLoad(img);
  7304. };
  7305. img.onerror = function (err) {
  7306. Tools.Error("Error while trying to load image: " + url);
  7307. if (onError) {
  7308. onError("Error while trying to load image: " + url, err);
  7309. }
  7310. };
  7311. var noIndexedDB = function () {
  7312. img.src = url;
  7313. };
  7314. var loadFromIndexedDB = function () {
  7315. if (database) {
  7316. database.loadImageFromDB(url, img);
  7317. }
  7318. };
  7319. //ANY database to do!
  7320. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7321. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7322. }
  7323. else {
  7324. if (url.indexOf("file:") !== -1) {
  7325. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7326. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7327. try {
  7328. var blobURL;
  7329. try {
  7330. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7331. }
  7332. catch (ex) {
  7333. // Chrome doesn't support oneTimeOnly parameter
  7334. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7335. }
  7336. img.src = blobURL;
  7337. }
  7338. catch (e) {
  7339. img.src = "";
  7340. }
  7341. return img;
  7342. }
  7343. }
  7344. noIndexedDB();
  7345. }
  7346. return img;
  7347. };
  7348. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7349. url = Tools.CleanUrl(url);
  7350. url = Tools.PreprocessUrl(url);
  7351. // If file and file input are set
  7352. if (url.indexOf("file:") !== -1) {
  7353. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7354. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7355. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7356. }
  7357. }
  7358. var loadUrl = Tools.BaseUrl + url;
  7359. var aborted = false;
  7360. var fileRequest = {
  7361. onCompleteObservable: new BABYLON.Observable(),
  7362. abort: function () { return aborted = true; },
  7363. };
  7364. var requestFile = function () {
  7365. var request = new XMLHttpRequest();
  7366. var retryHandle = null;
  7367. fileRequest.abort = function () {
  7368. aborted = true;
  7369. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7370. request.abort();
  7371. }
  7372. if (retryHandle !== null) {
  7373. clearTimeout(retryHandle);
  7374. retryHandle = null;
  7375. }
  7376. };
  7377. var retryLoop = function (retryIndex) {
  7378. request.open('GET', loadUrl, true);
  7379. if (useArrayBuffer) {
  7380. request.responseType = "arraybuffer";
  7381. }
  7382. if (onProgress) {
  7383. request.addEventListener("progress", onProgress);
  7384. }
  7385. var onLoadEnd = function () {
  7386. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7387. };
  7388. request.addEventListener("loadend", onLoadEnd);
  7389. var onReadyStateChange = function () {
  7390. if (aborted) {
  7391. return;
  7392. }
  7393. // In case of undefined state in some browsers.
  7394. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7395. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7396. request.removeEventListener("readystatechange", onReadyStateChange);
  7397. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7398. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7399. return;
  7400. }
  7401. var retryStrategy = Tools.DefaultRetryStrategy;
  7402. if (retryStrategy) {
  7403. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7404. if (waitTime !== -1) {
  7405. // Prevent the request from completing for retry.
  7406. request.removeEventListener("loadend", onLoadEnd);
  7407. request = new XMLHttpRequest();
  7408. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7409. return;
  7410. }
  7411. }
  7412. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7413. if (onError) {
  7414. onError(request, e);
  7415. }
  7416. else {
  7417. throw e;
  7418. }
  7419. }
  7420. };
  7421. request.addEventListener("readystatechange", onReadyStateChange);
  7422. request.send();
  7423. };
  7424. retryLoop(0);
  7425. };
  7426. // Caching all files
  7427. if (database && database.enableSceneOffline) {
  7428. var noIndexedDB_1 = function () {
  7429. if (!aborted) {
  7430. requestFile();
  7431. }
  7432. };
  7433. var loadFromIndexedDB = function () {
  7434. // TODO: database needs to support aborting and should return a IFileRequest
  7435. if (aborted) {
  7436. return;
  7437. }
  7438. if (database) {
  7439. database.loadFileFromDB(url, function (data) {
  7440. if (!aborted) {
  7441. onSuccess(data);
  7442. }
  7443. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7444. }, onProgress ? function (event) {
  7445. if (!aborted) {
  7446. onProgress(event);
  7447. }
  7448. } : undefined, noIndexedDB_1, useArrayBuffer);
  7449. }
  7450. };
  7451. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7452. }
  7453. else {
  7454. requestFile();
  7455. }
  7456. return fileRequest;
  7457. };
  7458. /**
  7459. * Load a script (identified by an url). When the url returns, the
  7460. * content of this file is added into a new script element, attached to the DOM (body element)
  7461. */
  7462. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7463. var head = document.getElementsByTagName('head')[0];
  7464. var script = document.createElement('script');
  7465. script.type = 'text/javascript';
  7466. script.src = scriptUrl;
  7467. script.onload = function () {
  7468. if (onSuccess) {
  7469. onSuccess();
  7470. }
  7471. };
  7472. script.onerror = function (e) {
  7473. if (onError) {
  7474. onError("Unable to load script", e);
  7475. }
  7476. };
  7477. head.appendChild(script);
  7478. };
  7479. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7480. var reader = new FileReader();
  7481. var request = {
  7482. onCompleteObservable: new BABYLON.Observable(),
  7483. abort: function () { return reader.abort(); },
  7484. };
  7485. reader.onloadend = function (e) {
  7486. request.onCompleteObservable.notifyObservers(request);
  7487. };
  7488. reader.onload = function (e) {
  7489. //target doesn't have result from ts 1.3
  7490. callback(e.target['result']);
  7491. };
  7492. reader.onprogress = progressCallback;
  7493. reader.readAsDataURL(fileToLoad);
  7494. return request;
  7495. };
  7496. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7497. var reader = new FileReader();
  7498. var request = {
  7499. onCompleteObservable: new BABYLON.Observable(),
  7500. abort: function () { return reader.abort(); },
  7501. };
  7502. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7503. reader.onerror = function (e) {
  7504. Tools.Log("Error while reading file: " + fileToLoad.name);
  7505. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7506. };
  7507. reader.onload = function (e) {
  7508. //target doesn't have result from ts 1.3
  7509. callback(e.target['result']);
  7510. };
  7511. if (progressCallBack) {
  7512. reader.onprogress = progressCallBack;
  7513. }
  7514. if (!useArrayBuffer) {
  7515. // Asynchronous read
  7516. reader.readAsText(fileToLoad);
  7517. }
  7518. else {
  7519. reader.readAsArrayBuffer(fileToLoad);
  7520. }
  7521. return request;
  7522. };
  7523. //returns a downloadable url to a file content.
  7524. Tools.FileAsURL = function (content) {
  7525. var fileBlob = new Blob([content]);
  7526. var url = window.URL || window.webkitURL;
  7527. var link = url.createObjectURL(fileBlob);
  7528. return link;
  7529. };
  7530. // Misc.
  7531. Tools.Format = function (value, decimals) {
  7532. if (decimals === void 0) { decimals = 2; }
  7533. return value.toFixed(decimals);
  7534. };
  7535. Tools.CheckExtends = function (v, min, max) {
  7536. if (v.x < min.x)
  7537. min.x = v.x;
  7538. if (v.y < min.y)
  7539. min.y = v.y;
  7540. if (v.z < min.z)
  7541. min.z = v.z;
  7542. if (v.x > max.x)
  7543. max.x = v.x;
  7544. if (v.y > max.y)
  7545. max.y = v.y;
  7546. if (v.z > max.z)
  7547. max.z = v.z;
  7548. };
  7549. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7550. for (var prop in source) {
  7551. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7552. continue;
  7553. }
  7554. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7555. continue;
  7556. }
  7557. var sourceValue = source[prop];
  7558. var typeOfSourceValue = typeof sourceValue;
  7559. if (typeOfSourceValue === "function") {
  7560. continue;
  7561. }
  7562. if (typeOfSourceValue === "object") {
  7563. if (sourceValue instanceof Array) {
  7564. destination[prop] = [];
  7565. if (sourceValue.length > 0) {
  7566. if (typeof sourceValue[0] == "object") {
  7567. for (var index = 0; index < sourceValue.length; index++) {
  7568. var clonedValue = cloneValue(sourceValue[index], destination);
  7569. if (destination[prop].indexOf(clonedValue) === -1) {
  7570. destination[prop].push(clonedValue);
  7571. }
  7572. }
  7573. }
  7574. else {
  7575. destination[prop] = sourceValue.slice(0);
  7576. }
  7577. }
  7578. }
  7579. else {
  7580. destination[prop] = cloneValue(sourceValue, destination);
  7581. }
  7582. }
  7583. else {
  7584. destination[prop] = sourceValue;
  7585. }
  7586. }
  7587. };
  7588. Tools.IsEmpty = function (obj) {
  7589. for (var i in obj) {
  7590. if (obj.hasOwnProperty(i)) {
  7591. return false;
  7592. }
  7593. }
  7594. return true;
  7595. };
  7596. Tools.RegisterTopRootEvents = function (events) {
  7597. for (var index = 0; index < events.length; index++) {
  7598. var event = events[index];
  7599. window.addEventListener(event.name, event.handler, false);
  7600. try {
  7601. if (window.parent) {
  7602. window.parent.addEventListener(event.name, event.handler, false);
  7603. }
  7604. }
  7605. catch (e) {
  7606. // Silently fails...
  7607. }
  7608. }
  7609. };
  7610. Tools.UnregisterTopRootEvents = function (events) {
  7611. for (var index = 0; index < events.length; index++) {
  7612. var event = events[index];
  7613. window.removeEventListener(event.name, event.handler);
  7614. try {
  7615. if (window.parent) {
  7616. window.parent.removeEventListener(event.name, event.handler);
  7617. }
  7618. }
  7619. catch (e) {
  7620. // Silently fails...
  7621. }
  7622. }
  7623. };
  7624. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7625. if (mimeType === void 0) { mimeType = "image/png"; }
  7626. // Read the contents of the framebuffer
  7627. var numberOfChannelsByLine = width * 4;
  7628. var halfHeight = height / 2;
  7629. //Reading datas from WebGL
  7630. var data = engine.readPixels(0, 0, width, height);
  7631. //To flip image on Y axis.
  7632. for (var i = 0; i < halfHeight; i++) {
  7633. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7634. var currentCell = j + i * numberOfChannelsByLine;
  7635. var targetLine = height - i - 1;
  7636. var targetCell = j + targetLine * numberOfChannelsByLine;
  7637. var temp = data[currentCell];
  7638. data[currentCell] = data[targetCell];
  7639. data[targetCell] = temp;
  7640. }
  7641. }
  7642. // Create a 2D canvas to store the result
  7643. if (!screenshotCanvas) {
  7644. screenshotCanvas = document.createElement('canvas');
  7645. }
  7646. screenshotCanvas.width = width;
  7647. screenshotCanvas.height = height;
  7648. var context = screenshotCanvas.getContext('2d');
  7649. if (context) {
  7650. // Copy the pixels to a 2D canvas
  7651. var imageData = context.createImageData(width, height);
  7652. var castData = (imageData.data);
  7653. castData.set(data);
  7654. context.putImageData(imageData, 0, 0);
  7655. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7656. }
  7657. };
  7658. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7659. if (mimeType === void 0) { mimeType = "image/png"; }
  7660. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7661. if (successCallback) {
  7662. successCallback(base64Image);
  7663. }
  7664. else {
  7665. // We need HTMLCanvasElement.toBlob for HD screenshots
  7666. if (!screenshotCanvas.toBlob) {
  7667. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7668. screenshotCanvas.toBlob = function (callback, type, quality) {
  7669. var _this = this;
  7670. setTimeout(function () {
  7671. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7672. for (var i = 0; i < len; i++) {
  7673. arr[i] = binStr.charCodeAt(i);
  7674. }
  7675. callback(new Blob([arr], { type: type || 'image/png' }));
  7676. });
  7677. };
  7678. }
  7679. screenshotCanvas.toBlob(function (blob) {
  7680. var url = URL.createObjectURL(blob);
  7681. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7682. if (("download" in document.createElement("a"))) {
  7683. var a = window.document.createElement("a");
  7684. a.href = url;
  7685. if (fileName) {
  7686. a.setAttribute("download", fileName);
  7687. }
  7688. else {
  7689. var date = new Date();
  7690. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7691. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7692. }
  7693. window.document.body.appendChild(a);
  7694. a.addEventListener("click", function () {
  7695. if (a.parentElement) {
  7696. a.parentElement.removeChild(a);
  7697. }
  7698. });
  7699. a.click();
  7700. }
  7701. else {
  7702. var newWindow = window.open("");
  7703. if (!newWindow)
  7704. return;
  7705. var img = newWindow.document.createElement("img");
  7706. img.onload = function () {
  7707. // no longer need to read the blob so it's revoked
  7708. URL.revokeObjectURL(url);
  7709. };
  7710. img.src = url;
  7711. newWindow.document.body.appendChild(img);
  7712. }
  7713. });
  7714. }
  7715. };
  7716. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7717. if (mimeType === void 0) { mimeType = "image/png"; }
  7718. var width;
  7719. var height;
  7720. // If a precision value is specified
  7721. if (size.precision) {
  7722. width = Math.round(engine.getRenderWidth() * size.precision);
  7723. height = Math.round(width / engine.getAspectRatio(camera));
  7724. }
  7725. else if (size.width && size.height) {
  7726. width = size.width;
  7727. height = size.height;
  7728. }
  7729. else if (size.width && !size.height) {
  7730. width = size.width;
  7731. height = Math.round(width / engine.getAspectRatio(camera));
  7732. }
  7733. else if (size.height && !size.width) {
  7734. height = size.height;
  7735. width = Math.round(height * engine.getAspectRatio(camera));
  7736. }
  7737. else if (!isNaN(size)) {
  7738. height = size;
  7739. width = size;
  7740. }
  7741. else {
  7742. Tools.Error("Invalid 'size' parameter !");
  7743. return;
  7744. }
  7745. if (!screenshotCanvas) {
  7746. screenshotCanvas = document.createElement('canvas');
  7747. }
  7748. screenshotCanvas.width = width;
  7749. screenshotCanvas.height = height;
  7750. var renderContext = screenshotCanvas.getContext("2d");
  7751. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7752. var newWidth = width;
  7753. var newHeight = newWidth / ratio;
  7754. if (newHeight > height) {
  7755. newHeight = height;
  7756. newWidth = newHeight * ratio;
  7757. }
  7758. var offsetX = Math.max(0, width - newWidth) / 2;
  7759. var offsetY = Math.max(0, height - newHeight) / 2;
  7760. var renderingCanvas = engine.getRenderingCanvas();
  7761. if (renderContext && renderingCanvas) {
  7762. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7763. }
  7764. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7765. };
  7766. /**
  7767. * Generates an image screenshot from the specified camera.
  7768. *
  7769. * @param engine The engine to use for rendering
  7770. * @param camera The camera to use for rendering
  7771. * @param size This parameter can be set to a single number or to an object with the
  7772. * following (optional) properties: precision, width, height. If a single number is passed,
  7773. * it will be used for both width and height. If an object is passed, the screenshot size
  7774. * will be derived from the parameters. The precision property is a multiplier allowing
  7775. * rendering at a higher or lower resolution.
  7776. * @param successCallback The callback receives a single parameter which contains the
  7777. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7778. * src parameter of an <img> to display it.
  7779. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7780. * Check your browser for supported MIME types.
  7781. * @param samples Texture samples (default: 1)
  7782. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7783. * @param fileName A name for for the downloaded file.
  7784. * @constructor
  7785. */
  7786. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7787. if (mimeType === void 0) { mimeType = "image/png"; }
  7788. if (samples === void 0) { samples = 1; }
  7789. if (antialiasing === void 0) { antialiasing = false; }
  7790. var width;
  7791. var height;
  7792. //If a precision value is specified
  7793. if (size.precision) {
  7794. width = Math.round(engine.getRenderWidth() * size.precision);
  7795. height = Math.round(width / engine.getAspectRatio(camera));
  7796. size = { width: width, height: height };
  7797. }
  7798. else if (size.width && size.height) {
  7799. width = size.width;
  7800. height = size.height;
  7801. }
  7802. else if (size.width && !size.height) {
  7803. width = size.width;
  7804. height = Math.round(width / engine.getAspectRatio(camera));
  7805. size = { width: width, height: height };
  7806. }
  7807. else if (size.height && !size.width) {
  7808. height = size.height;
  7809. width = Math.round(height * engine.getAspectRatio(camera));
  7810. size = { width: width, height: height };
  7811. }
  7812. else if (!isNaN(size)) {
  7813. height = size;
  7814. width = size;
  7815. }
  7816. else {
  7817. Tools.Error("Invalid 'size' parameter !");
  7818. return;
  7819. }
  7820. var scene = camera.getScene();
  7821. var previousCamera = null;
  7822. if (scene.activeCamera !== camera) {
  7823. previousCamera = scene.activeCamera;
  7824. scene.activeCamera = camera;
  7825. }
  7826. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7827. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7828. texture.renderList = null;
  7829. texture.samples = samples;
  7830. if (antialiasing) {
  7831. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7832. }
  7833. texture.onAfterRenderObservable.add(function () {
  7834. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7835. });
  7836. scene.incrementRenderId();
  7837. scene.resetCachedMaterial();
  7838. texture.render(true);
  7839. texture.dispose();
  7840. if (previousCamera) {
  7841. scene.activeCamera = previousCamera;
  7842. }
  7843. camera.getProjectionMatrix(true); // Force cache refresh;
  7844. };
  7845. // XHR response validator for local file scenario
  7846. Tools.ValidateXHRData = function (xhr, dataType) {
  7847. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7848. if (dataType === void 0) { dataType = 7; }
  7849. try {
  7850. if (dataType & 1) {
  7851. if (xhr.responseText && xhr.responseText.length > 0) {
  7852. return true;
  7853. }
  7854. else if (dataType === 1) {
  7855. return false;
  7856. }
  7857. }
  7858. if (dataType & 2) {
  7859. // Check header width and height since there is no "TGA" magic number
  7860. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7861. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7862. return true;
  7863. }
  7864. else if (dataType === 2) {
  7865. return false;
  7866. }
  7867. }
  7868. if (dataType & 4) {
  7869. // Check for the "DDS" magic number
  7870. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7871. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7872. return true;
  7873. }
  7874. else {
  7875. return false;
  7876. }
  7877. }
  7878. }
  7879. catch (e) {
  7880. // Global protection
  7881. }
  7882. return false;
  7883. };
  7884. /**
  7885. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7886. * Be aware Math.random() could cause collisions, but:
  7887. * "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"
  7888. */
  7889. Tools.RandomId = function () {
  7890. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7891. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7892. return v.toString(16);
  7893. });
  7894. };
  7895. /**
  7896. * Test if the given uri is a base64 string.
  7897. * @param uri The uri to test
  7898. * @return True if the uri is a base64 string or false otherwise.
  7899. */
  7900. Tools.IsBase64 = function (uri) {
  7901. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  7902. };
  7903. /**
  7904. * Decode the given base64 uri.
  7905. * @param uri The uri to decode
  7906. * @return The decoded base64 data.
  7907. */
  7908. Tools.DecodeBase64 = function (uri) {
  7909. var decodedString = atob(uri.split(",")[1]);
  7910. var bufferLength = decodedString.length;
  7911. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  7912. for (var i = 0; i < bufferLength; i++) {
  7913. bufferView[i] = decodedString.charCodeAt(i);
  7914. }
  7915. return bufferView.buffer;
  7916. };
  7917. Object.defineProperty(Tools, "NoneLogLevel", {
  7918. get: function () {
  7919. return Tools._NoneLogLevel;
  7920. },
  7921. enumerable: true,
  7922. configurable: true
  7923. });
  7924. Object.defineProperty(Tools, "MessageLogLevel", {
  7925. get: function () {
  7926. return Tools._MessageLogLevel;
  7927. },
  7928. enumerable: true,
  7929. configurable: true
  7930. });
  7931. Object.defineProperty(Tools, "WarningLogLevel", {
  7932. get: function () {
  7933. return Tools._WarningLogLevel;
  7934. },
  7935. enumerable: true,
  7936. configurable: true
  7937. });
  7938. Object.defineProperty(Tools, "ErrorLogLevel", {
  7939. get: function () {
  7940. return Tools._ErrorLogLevel;
  7941. },
  7942. enumerable: true,
  7943. configurable: true
  7944. });
  7945. Object.defineProperty(Tools, "AllLogLevel", {
  7946. get: function () {
  7947. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7948. },
  7949. enumerable: true,
  7950. configurable: true
  7951. });
  7952. Tools._AddLogEntry = function (entry) {
  7953. Tools._LogCache = entry + Tools._LogCache;
  7954. if (Tools.OnNewCacheEntry) {
  7955. Tools.OnNewCacheEntry(entry);
  7956. }
  7957. };
  7958. Tools._FormatMessage = function (message) {
  7959. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7960. var date = new Date();
  7961. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7962. };
  7963. Tools._LogDisabled = function (message) {
  7964. // nothing to do
  7965. };
  7966. Tools._LogEnabled = function (message) {
  7967. var formattedMessage = Tools._FormatMessage(message);
  7968. console.log("BJS - " + formattedMessage);
  7969. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7970. Tools._AddLogEntry(entry);
  7971. };
  7972. Tools._WarnDisabled = function (message) {
  7973. // nothing to do
  7974. };
  7975. Tools._WarnEnabled = function (message) {
  7976. var formattedMessage = Tools._FormatMessage(message);
  7977. console.warn("BJS - " + formattedMessage);
  7978. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7979. Tools._AddLogEntry(entry);
  7980. };
  7981. Tools._ErrorDisabled = function (message) {
  7982. // nothing to do
  7983. };
  7984. Tools._ErrorEnabled = function (message) {
  7985. Tools.errorsCount++;
  7986. var formattedMessage = Tools._FormatMessage(message);
  7987. console.error("BJS - " + formattedMessage);
  7988. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7989. Tools._AddLogEntry(entry);
  7990. };
  7991. Object.defineProperty(Tools, "LogCache", {
  7992. get: function () {
  7993. return Tools._LogCache;
  7994. },
  7995. enumerable: true,
  7996. configurable: true
  7997. });
  7998. Tools.ClearLogCache = function () {
  7999. Tools._LogCache = "";
  8000. Tools.errorsCount = 0;
  8001. };
  8002. Object.defineProperty(Tools, "LogLevels", {
  8003. set: function (level) {
  8004. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8005. Tools.Log = Tools._LogEnabled;
  8006. }
  8007. else {
  8008. Tools.Log = Tools._LogDisabled;
  8009. }
  8010. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8011. Tools.Warn = Tools._WarnEnabled;
  8012. }
  8013. else {
  8014. Tools.Warn = Tools._WarnDisabled;
  8015. }
  8016. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8017. Tools.Error = Tools._ErrorEnabled;
  8018. }
  8019. else {
  8020. Tools.Error = Tools._ErrorDisabled;
  8021. }
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Tools.IsWindowObjectExist = function () {
  8027. return (typeof window) !== "undefined";
  8028. };
  8029. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8030. get: function () {
  8031. return Tools._PerformanceNoneLogLevel;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8037. get: function () {
  8038. return Tools._PerformanceUserMarkLogLevel;
  8039. },
  8040. enumerable: true,
  8041. configurable: true
  8042. });
  8043. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8044. get: function () {
  8045. return Tools._PerformanceConsoleLogLevel;
  8046. },
  8047. enumerable: true,
  8048. configurable: true
  8049. });
  8050. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8051. set: function (level) {
  8052. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8053. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8054. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8055. return;
  8056. }
  8057. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8058. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8059. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8060. return;
  8061. }
  8062. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8063. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8064. },
  8065. enumerable: true,
  8066. configurable: true
  8067. });
  8068. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8069. };
  8070. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8071. };
  8072. Tools._StartUserMark = function (counterName, condition) {
  8073. if (condition === void 0) { condition = true; }
  8074. if (!Tools._performance) {
  8075. if (!Tools.IsWindowObjectExist()) {
  8076. return;
  8077. }
  8078. Tools._performance = window.performance;
  8079. }
  8080. if (!condition || !Tools._performance.mark) {
  8081. return;
  8082. }
  8083. Tools._performance.mark(counterName + "-Begin");
  8084. };
  8085. Tools._EndUserMark = function (counterName, condition) {
  8086. if (condition === void 0) { condition = true; }
  8087. if (!condition || !Tools._performance.mark) {
  8088. return;
  8089. }
  8090. Tools._performance.mark(counterName + "-End");
  8091. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8092. };
  8093. Tools._StartPerformanceConsole = function (counterName, condition) {
  8094. if (condition === void 0) { condition = true; }
  8095. if (!condition) {
  8096. return;
  8097. }
  8098. Tools._StartUserMark(counterName, condition);
  8099. if (console.time) {
  8100. console.time(counterName);
  8101. }
  8102. };
  8103. Tools._EndPerformanceConsole = function (counterName, condition) {
  8104. if (condition === void 0) { condition = true; }
  8105. if (!condition) {
  8106. return;
  8107. }
  8108. Tools._EndUserMark(counterName, condition);
  8109. if (console.time) {
  8110. console.timeEnd(counterName);
  8111. }
  8112. };
  8113. Object.defineProperty(Tools, "Now", {
  8114. get: function () {
  8115. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8116. return window.performance.now();
  8117. }
  8118. return new Date().getTime();
  8119. },
  8120. enumerable: true,
  8121. configurable: true
  8122. });
  8123. /**
  8124. * This method will return the name of the class used to create the instance of the given object.
  8125. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8126. * @param object the object to get the class name from
  8127. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8128. */
  8129. Tools.GetClassName = function (object, isType) {
  8130. if (isType === void 0) { isType = false; }
  8131. var name = null;
  8132. if (!isType && object.getClassName) {
  8133. name = object.getClassName();
  8134. }
  8135. else {
  8136. if (object instanceof Object) {
  8137. var classObj = isType ? object : Object.getPrototypeOf(object);
  8138. name = classObj.constructor["__bjsclassName__"];
  8139. }
  8140. if (!name) {
  8141. name = typeof object;
  8142. }
  8143. }
  8144. return name;
  8145. };
  8146. Tools.First = function (array, predicate) {
  8147. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8148. var el = array_1[_i];
  8149. if (predicate(el)) {
  8150. return el;
  8151. }
  8152. }
  8153. return null;
  8154. };
  8155. /**
  8156. * This method will return the name of the full name of the class, including its owning module (if any).
  8157. * 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).
  8158. * @param object the object to get the class name from
  8159. * @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.
  8160. */
  8161. Tools.getFullClassName = function (object, isType) {
  8162. if (isType === void 0) { isType = false; }
  8163. var className = null;
  8164. var moduleName = null;
  8165. if (!isType && object.getClassName) {
  8166. className = object.getClassName();
  8167. }
  8168. else {
  8169. if (object instanceof Object) {
  8170. var classObj = isType ? object : Object.getPrototypeOf(object);
  8171. className = classObj.constructor["__bjsclassName__"];
  8172. moduleName = classObj.constructor["__bjsmoduleName__"];
  8173. }
  8174. if (!className) {
  8175. className = typeof object;
  8176. }
  8177. }
  8178. if (!className) {
  8179. return null;
  8180. }
  8181. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8182. };
  8183. /**
  8184. * 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.
  8185. * @param array
  8186. */
  8187. Tools.arrayOrStringFeeder = function (array) {
  8188. return function (index) {
  8189. if (index >= array.length) {
  8190. return null;
  8191. }
  8192. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8193. if (val && val.getHashCode) {
  8194. val = val.getHashCode();
  8195. }
  8196. if (typeof val === "string") {
  8197. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8198. }
  8199. return val;
  8200. };
  8201. };
  8202. /**
  8203. * Compute the hashCode of a stream of number
  8204. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8205. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8206. * @return the hash code computed
  8207. */
  8208. Tools.hashCodeFromStream = function (feeder) {
  8209. // Based from here: http://stackoverflow.com/a/7616484/802124
  8210. var hash = 0;
  8211. var index = 0;
  8212. var chr = feeder(index++);
  8213. while (chr != null) {
  8214. hash = ((hash << 5) - hash) + chr;
  8215. hash |= 0; // Convert to 32bit integer
  8216. chr = feeder(index++);
  8217. }
  8218. return hash;
  8219. };
  8220. Tools.BaseUrl = "";
  8221. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8222. /**
  8223. * Default behaviour for cors in the application.
  8224. * It can be a string if the expected behavior is identical in the entire app.
  8225. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8226. */
  8227. Tools.CorsBehavior = "anonymous";
  8228. Tools.UseFallbackTexture = true;
  8229. /**
  8230. * Use this object to register external classes like custom textures or material
  8231. * to allow the laoders to instantiate them
  8232. */
  8233. Tools.RegisteredExternalClasses = {};
  8234. // Used in case of a texture loading problem
  8235. 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";
  8236. Tools.PreprocessUrl = function (url) {
  8237. return url;
  8238. };
  8239. // Logs
  8240. Tools._NoneLogLevel = 0;
  8241. Tools._MessageLogLevel = 1;
  8242. Tools._WarningLogLevel = 2;
  8243. Tools._ErrorLogLevel = 4;
  8244. Tools._LogCache = "";
  8245. Tools.errorsCount = 0;
  8246. Tools.Log = Tools._LogEnabled;
  8247. Tools.Warn = Tools._WarnEnabled;
  8248. Tools.Error = Tools._ErrorEnabled;
  8249. // Performances
  8250. Tools._PerformanceNoneLogLevel = 0;
  8251. Tools._PerformanceUserMarkLogLevel = 1;
  8252. Tools._PerformanceConsoleLogLevel = 2;
  8253. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8254. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8255. return Tools;
  8256. }());
  8257. BABYLON.Tools = Tools;
  8258. /**
  8259. * This class is used to track a performance counter which is number based.
  8260. * The user has access to many properties which give statistics of different nature
  8261. *
  8262. * The implementer can track two kinds of Performance Counter: time and count
  8263. * 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.
  8264. * 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.
  8265. */
  8266. var PerfCounter = /** @class */ (function () {
  8267. function PerfCounter() {
  8268. this._startMonitoringTime = 0;
  8269. this._min = 0;
  8270. this._max = 0;
  8271. this._average = 0;
  8272. this._lastSecAverage = 0;
  8273. this._current = 0;
  8274. this._totalValueCount = 0;
  8275. this._totalAccumulated = 0;
  8276. this._lastSecAccumulated = 0;
  8277. this._lastSecTime = 0;
  8278. this._lastSecValueCount = 0;
  8279. }
  8280. Object.defineProperty(PerfCounter.prototype, "min", {
  8281. /**
  8282. * Returns the smallest value ever
  8283. */
  8284. get: function () {
  8285. return this._min;
  8286. },
  8287. enumerable: true,
  8288. configurable: true
  8289. });
  8290. Object.defineProperty(PerfCounter.prototype, "max", {
  8291. /**
  8292. * Returns the biggest value ever
  8293. */
  8294. get: function () {
  8295. return this._max;
  8296. },
  8297. enumerable: true,
  8298. configurable: true
  8299. });
  8300. Object.defineProperty(PerfCounter.prototype, "average", {
  8301. /**
  8302. * Returns the average value since the performance counter is running
  8303. */
  8304. get: function () {
  8305. return this._average;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8311. /**
  8312. * Returns the average value of the last second the counter was monitored
  8313. */
  8314. get: function () {
  8315. return this._lastSecAverage;
  8316. },
  8317. enumerable: true,
  8318. configurable: true
  8319. });
  8320. Object.defineProperty(PerfCounter.prototype, "current", {
  8321. /**
  8322. * Returns the current value
  8323. */
  8324. get: function () {
  8325. return this._current;
  8326. },
  8327. enumerable: true,
  8328. configurable: true
  8329. });
  8330. Object.defineProperty(PerfCounter.prototype, "total", {
  8331. get: function () {
  8332. return this._totalAccumulated;
  8333. },
  8334. enumerable: true,
  8335. configurable: true
  8336. });
  8337. Object.defineProperty(PerfCounter.prototype, "count", {
  8338. get: function () {
  8339. return this._totalValueCount;
  8340. },
  8341. enumerable: true,
  8342. configurable: true
  8343. });
  8344. /**
  8345. * Call this method to start monitoring a new frame.
  8346. * 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.
  8347. */
  8348. PerfCounter.prototype.fetchNewFrame = function () {
  8349. this._totalValueCount++;
  8350. this._current = 0;
  8351. this._lastSecValueCount++;
  8352. };
  8353. /**
  8354. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8355. * @param newCount the count value to add to the monitored count
  8356. * @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.
  8357. */
  8358. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8359. if (!PerfCounter.Enabled) {
  8360. return;
  8361. }
  8362. this._current += newCount;
  8363. if (fetchResult) {
  8364. this._fetchResult();
  8365. }
  8366. };
  8367. /**
  8368. * Start monitoring this performance counter
  8369. */
  8370. PerfCounter.prototype.beginMonitoring = function () {
  8371. if (!PerfCounter.Enabled) {
  8372. return;
  8373. }
  8374. this._startMonitoringTime = Tools.Now;
  8375. };
  8376. /**
  8377. * Compute the time lapsed since the previous beginMonitoring() call.
  8378. * @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
  8379. */
  8380. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8381. if (newFrame === void 0) { newFrame = true; }
  8382. if (!PerfCounter.Enabled) {
  8383. return;
  8384. }
  8385. if (newFrame) {
  8386. this.fetchNewFrame();
  8387. }
  8388. var currentTime = Tools.Now;
  8389. this._current = currentTime - this._startMonitoringTime;
  8390. if (newFrame) {
  8391. this._fetchResult();
  8392. }
  8393. };
  8394. PerfCounter.prototype._fetchResult = function () {
  8395. this._totalAccumulated += this._current;
  8396. this._lastSecAccumulated += this._current;
  8397. // Min/Max update
  8398. this._min = Math.min(this._min, this._current);
  8399. this._max = Math.max(this._max, this._current);
  8400. this._average = this._totalAccumulated / this._totalValueCount;
  8401. // Reset last sec?
  8402. var now = Tools.Now;
  8403. if ((now - this._lastSecTime) > 1000) {
  8404. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8405. this._lastSecTime = now;
  8406. this._lastSecAccumulated = 0;
  8407. this._lastSecValueCount = 0;
  8408. }
  8409. };
  8410. PerfCounter.Enabled = true;
  8411. return PerfCounter;
  8412. }());
  8413. BABYLON.PerfCounter = PerfCounter;
  8414. /**
  8415. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8416. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8417. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8418. * @param name The name of the class, case should be preserved
  8419. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8420. */
  8421. function className(name, module) {
  8422. return function (target) {
  8423. target["__bjsclassName__"] = name;
  8424. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8425. };
  8426. }
  8427. BABYLON.className = className;
  8428. /**
  8429. * An implementation of a loop for asynchronous functions.
  8430. */
  8431. var AsyncLoop = /** @class */ (function () {
  8432. /**
  8433. * Constroctor.
  8434. * @param iterations the number of iterations.
  8435. * @param _fn the function to run each iteration
  8436. * @param _successCallback the callback that will be called upon succesful execution
  8437. * @param offset starting offset.
  8438. */
  8439. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8440. if (offset === void 0) { offset = 0; }
  8441. this.iterations = iterations;
  8442. this._fn = _fn;
  8443. this._successCallback = _successCallback;
  8444. this.index = offset - 1;
  8445. this._done = false;
  8446. }
  8447. /**
  8448. * Execute the next iteration. Must be called after the last iteration was finished.
  8449. */
  8450. AsyncLoop.prototype.executeNext = function () {
  8451. if (!this._done) {
  8452. if (this.index + 1 < this.iterations) {
  8453. ++this.index;
  8454. this._fn(this);
  8455. }
  8456. else {
  8457. this.breakLoop();
  8458. }
  8459. }
  8460. };
  8461. /**
  8462. * Break the loop and run the success callback.
  8463. */
  8464. AsyncLoop.prototype.breakLoop = function () {
  8465. this._done = true;
  8466. this._successCallback();
  8467. };
  8468. /**
  8469. * Helper function
  8470. */
  8471. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8472. if (offset === void 0) { offset = 0; }
  8473. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8474. loop.executeNext();
  8475. return loop;
  8476. };
  8477. /**
  8478. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8479. * @param iterations total number of iterations
  8480. * @param syncedIterations number of synchronous iterations in each async iteration.
  8481. * @param fn the function to call each iteration.
  8482. * @param callback a success call back that will be called when iterating stops.
  8483. * @param breakFunction a break condition (optional)
  8484. * @param timeout timeout settings for the setTimeout function. default - 0.
  8485. * @constructor
  8486. */
  8487. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8488. if (timeout === void 0) { timeout = 0; }
  8489. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8490. if (breakFunction && breakFunction())
  8491. loop.breakLoop();
  8492. else {
  8493. setTimeout(function () {
  8494. for (var i = 0; i < syncedIterations; ++i) {
  8495. var iteration = (loop.index * syncedIterations) + i;
  8496. if (iteration >= iterations)
  8497. break;
  8498. fn(iteration);
  8499. if (breakFunction && breakFunction()) {
  8500. loop.breakLoop();
  8501. break;
  8502. }
  8503. }
  8504. loop.executeNext();
  8505. }, timeout);
  8506. }
  8507. }, callback);
  8508. };
  8509. return AsyncLoop;
  8510. }());
  8511. BABYLON.AsyncLoop = AsyncLoop;
  8512. })(BABYLON || (BABYLON = {}));
  8513. //# sourceMappingURL=babylon.tools.js.map
  8514. var BABYLON;
  8515. (function (BABYLON) {
  8516. var PromiseStates;
  8517. (function (PromiseStates) {
  8518. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8519. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8520. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8521. })(PromiseStates || (PromiseStates = {}));
  8522. var FulFillmentAgregator = /** @class */ (function () {
  8523. function FulFillmentAgregator() {
  8524. this.count = 0;
  8525. this.target = 0;
  8526. this.results = [];
  8527. }
  8528. return FulFillmentAgregator;
  8529. }());
  8530. var InternalPromise = /** @class */ (function () {
  8531. function InternalPromise(resolver) {
  8532. var _this = this;
  8533. this._state = PromiseStates.Pending;
  8534. this._children = new Array();
  8535. this._rejectWasConsumed = false;
  8536. if (!resolver) {
  8537. return;
  8538. }
  8539. try {
  8540. resolver(function (value) {
  8541. _this._resolve(value);
  8542. }, function (reason) {
  8543. _this._reject(reason);
  8544. });
  8545. }
  8546. catch (e) {
  8547. this._reject(e.message);
  8548. }
  8549. }
  8550. Object.defineProperty(InternalPromise.prototype, "state", {
  8551. get: function () {
  8552. return this._state;
  8553. },
  8554. enumerable: true,
  8555. configurable: true
  8556. });
  8557. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8558. get: function () {
  8559. return this._state === PromiseStates.Fulfilled;
  8560. },
  8561. enumerable: true,
  8562. configurable: true
  8563. });
  8564. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8565. get: function () {
  8566. return this._state === PromiseStates.Rejected;
  8567. },
  8568. enumerable: true,
  8569. configurable: true
  8570. });
  8571. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8572. get: function () {
  8573. return this._state === PromiseStates.Pending;
  8574. },
  8575. enumerable: true,
  8576. configurable: true
  8577. });
  8578. InternalPromise.prototype.value = function () {
  8579. if (!this.isFulfilled) {
  8580. throw new Error("Promise is not fulfilled");
  8581. }
  8582. return this._result;
  8583. };
  8584. InternalPromise.prototype.reason = function () {
  8585. if (!this.isRejected) {
  8586. throw new Error("Promise is not rejected");
  8587. }
  8588. return this._reason;
  8589. };
  8590. InternalPromise.prototype.catch = function (onRejected) {
  8591. return this.then(undefined, onRejected);
  8592. };
  8593. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8594. var newPromise = new InternalPromise();
  8595. newPromise._onFulfilled = onFulfilled;
  8596. newPromise._onRejected = onRejected;
  8597. // Composition
  8598. this._children.push(newPromise);
  8599. if (this._state !== PromiseStates.Pending) {
  8600. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8601. var returnedValue = newPromise._resolve(this._result);
  8602. if (returnedValue !== undefined && returnedValue !== null) {
  8603. if (returnedValue._state !== undefined) {
  8604. var returnedPromise = returnedValue;
  8605. newPromise._children.push(returnedPromise);
  8606. newPromise = returnedPromise;
  8607. }
  8608. else {
  8609. newPromise._result = returnedValue;
  8610. }
  8611. }
  8612. }
  8613. else {
  8614. newPromise._reject(this._reason);
  8615. }
  8616. }
  8617. return newPromise;
  8618. };
  8619. InternalPromise.prototype._moveChildren = function (children) {
  8620. this._children = children.splice(0, children.length);
  8621. if (this.isFulfilled) {
  8622. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8623. var child = _a[_i];
  8624. child._resolve(this._result);
  8625. }
  8626. }
  8627. else if (this.isRejected) {
  8628. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  8629. var child = _c[_b];
  8630. child._reject(this._reason);
  8631. }
  8632. }
  8633. };
  8634. InternalPromise.prototype._resolve = function (value) {
  8635. try {
  8636. this._state = PromiseStates.Fulfilled;
  8637. this._result = value;
  8638. var returnedValue = null;
  8639. if (this._onFulfilled) {
  8640. returnedValue = this._onFulfilled(value);
  8641. }
  8642. if (returnedValue !== undefined && returnedValue !== null) {
  8643. if (returnedValue._state !== undefined) {
  8644. // Transmit children
  8645. var returnedPromise = returnedValue;
  8646. returnedPromise._moveChildren(this._children);
  8647. }
  8648. }
  8649. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8650. var child = _a[_i];
  8651. child._resolve(value);
  8652. }
  8653. return returnedValue;
  8654. }
  8655. catch (e) {
  8656. this._reject(e.message);
  8657. }
  8658. return null;
  8659. };
  8660. InternalPromise.prototype._reject = function (reason) {
  8661. this._state = PromiseStates.Rejected;
  8662. this._reason = reason;
  8663. if (this._onRejected) {
  8664. this._onRejected(reason);
  8665. this._rejectWasConsumed = true;
  8666. }
  8667. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8668. var child = _a[_i];
  8669. if (this._rejectWasConsumed) {
  8670. child._resolve(null);
  8671. }
  8672. else {
  8673. child._reject(reason);
  8674. }
  8675. }
  8676. };
  8677. InternalPromise.resolve = function (value) {
  8678. var newPromise = new InternalPromise();
  8679. newPromise._resolve(value);
  8680. return newPromise;
  8681. };
  8682. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8683. promise.then(function (value) {
  8684. agregator.results[index] = value;
  8685. agregator.count++;
  8686. if (agregator.count === agregator.target) {
  8687. agregator.rootPromise._resolve(agregator.results);
  8688. }
  8689. return null;
  8690. }, function (reason) {
  8691. if (!agregator.rootPromise.isRejected) {
  8692. agregator.rootPromise._reject(reason);
  8693. }
  8694. });
  8695. };
  8696. InternalPromise.all = function (promises) {
  8697. var newPromise = new InternalPromise();
  8698. var agregator = new FulFillmentAgregator();
  8699. agregator.target = promises.length;
  8700. agregator.rootPromise = newPromise;
  8701. for (var index = 0; index < promises.length; index++) {
  8702. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8703. }
  8704. return newPromise;
  8705. };
  8706. return InternalPromise;
  8707. }());
  8708. /**
  8709. * Helper class that provides a small promise polyfill
  8710. */
  8711. var PromisePolyfill = /** @class */ (function () {
  8712. function PromisePolyfill() {
  8713. }
  8714. /**
  8715. * Static function used to check if the polyfill is required
  8716. * If this is the case then the function will inject the polyfill to window.Promise
  8717. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8718. */
  8719. PromisePolyfill.Apply = function (force) {
  8720. if (force === void 0) { force = false; }
  8721. if (force || typeof Promise === 'undefined') {
  8722. var root = window;
  8723. root.Promise = InternalPromise;
  8724. }
  8725. };
  8726. return PromisePolyfill;
  8727. }());
  8728. BABYLON.PromisePolyfill = PromisePolyfill;
  8729. })(BABYLON || (BABYLON = {}));
  8730. //# sourceMappingURL=babylon.promise.js.map
  8731. var BABYLON;
  8732. (function (BABYLON) {
  8733. var _AlphaState = /** @class */ (function () {
  8734. /**
  8735. * Initializes the state.
  8736. */
  8737. function _AlphaState() {
  8738. this._isAlphaBlendDirty = false;
  8739. this._isBlendFunctionParametersDirty = false;
  8740. this._isBlendEquationParametersDirty = false;
  8741. this._isBlendConstantsDirty = false;
  8742. this._alphaBlend = false;
  8743. this._blendFunctionParameters = new Array(4);
  8744. this._blendEquationParameters = new Array(2);
  8745. this._blendConstants = new Array(4);
  8746. this.reset();
  8747. }
  8748. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8749. get: function () {
  8750. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8751. },
  8752. enumerable: true,
  8753. configurable: true
  8754. });
  8755. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8756. get: function () {
  8757. return this._alphaBlend;
  8758. },
  8759. set: function (value) {
  8760. if (this._alphaBlend === value) {
  8761. return;
  8762. }
  8763. this._alphaBlend = value;
  8764. this._isAlphaBlendDirty = true;
  8765. },
  8766. enumerable: true,
  8767. configurable: true
  8768. });
  8769. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8770. if (this._blendConstants[0] === r &&
  8771. this._blendConstants[1] === g &&
  8772. this._blendConstants[2] === b &&
  8773. this._blendConstants[3] === a) {
  8774. return;
  8775. }
  8776. this._blendConstants[0] = r;
  8777. this._blendConstants[1] = g;
  8778. this._blendConstants[2] = b;
  8779. this._blendConstants[3] = a;
  8780. this._isBlendConstantsDirty = true;
  8781. };
  8782. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8783. if (this._blendFunctionParameters[0] === value0 &&
  8784. this._blendFunctionParameters[1] === value1 &&
  8785. this._blendFunctionParameters[2] === value2 &&
  8786. this._blendFunctionParameters[3] === value3) {
  8787. return;
  8788. }
  8789. this._blendFunctionParameters[0] = value0;
  8790. this._blendFunctionParameters[1] = value1;
  8791. this._blendFunctionParameters[2] = value2;
  8792. this._blendFunctionParameters[3] = value3;
  8793. this._isBlendFunctionParametersDirty = true;
  8794. };
  8795. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8796. if (this._blendEquationParameters[0] === rgb &&
  8797. this._blendEquationParameters[1] === alpha) {
  8798. return;
  8799. }
  8800. this._blendEquationParameters[0] = rgb;
  8801. this._blendEquationParameters[1] = alpha;
  8802. this._isBlendEquationParametersDirty = true;
  8803. };
  8804. _AlphaState.prototype.reset = function () {
  8805. this._alphaBlend = false;
  8806. this._blendFunctionParameters[0] = null;
  8807. this._blendFunctionParameters[1] = null;
  8808. this._blendFunctionParameters[2] = null;
  8809. this._blendFunctionParameters[3] = null;
  8810. this._blendEquationParameters[0] = null;
  8811. this._blendEquationParameters[1] = null;
  8812. this._blendConstants[0] = null;
  8813. this._blendConstants[1] = null;
  8814. this._blendConstants[2] = null;
  8815. this._blendConstants[3] = null;
  8816. this._isAlphaBlendDirty = true;
  8817. this._isBlendFunctionParametersDirty = false;
  8818. this._isBlendEquationParametersDirty = false;
  8819. this._isBlendConstantsDirty = false;
  8820. };
  8821. _AlphaState.prototype.apply = function (gl) {
  8822. if (!this.isDirty) {
  8823. return;
  8824. }
  8825. // Alpha blend
  8826. if (this._isAlphaBlendDirty) {
  8827. if (this._alphaBlend) {
  8828. gl.enable(gl.BLEND);
  8829. }
  8830. else {
  8831. gl.disable(gl.BLEND);
  8832. }
  8833. this._isAlphaBlendDirty = false;
  8834. }
  8835. // Alpha function
  8836. if (this._isBlendFunctionParametersDirty) {
  8837. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8838. this._isBlendFunctionParametersDirty = false;
  8839. }
  8840. // Alpha equation
  8841. if (this._isBlendEquationParametersDirty) {
  8842. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8843. this._isBlendEquationParametersDirty = false;
  8844. }
  8845. // Constants
  8846. if (this._isBlendConstantsDirty) {
  8847. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8848. this._isBlendConstantsDirty = false;
  8849. }
  8850. };
  8851. return _AlphaState;
  8852. }());
  8853. BABYLON._AlphaState = _AlphaState;
  8854. })(BABYLON || (BABYLON = {}));
  8855. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8856. var BABYLON;
  8857. (function (BABYLON) {
  8858. var _DepthCullingState = /** @class */ (function () {
  8859. /**
  8860. * Initializes the state.
  8861. */
  8862. function _DepthCullingState() {
  8863. this._isDepthTestDirty = false;
  8864. this._isDepthMaskDirty = false;
  8865. this._isDepthFuncDirty = false;
  8866. this._isCullFaceDirty = false;
  8867. this._isCullDirty = false;
  8868. this._isZOffsetDirty = false;
  8869. this._isFrontFaceDirty = false;
  8870. this.reset();
  8871. }
  8872. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8873. get: function () {
  8874. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8875. },
  8876. enumerable: true,
  8877. configurable: true
  8878. });
  8879. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8880. get: function () {
  8881. return this._zOffset;
  8882. },
  8883. set: function (value) {
  8884. if (this._zOffset === value) {
  8885. return;
  8886. }
  8887. this._zOffset = value;
  8888. this._isZOffsetDirty = true;
  8889. },
  8890. enumerable: true,
  8891. configurable: true
  8892. });
  8893. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8894. get: function () {
  8895. return this._cullFace;
  8896. },
  8897. set: function (value) {
  8898. if (this._cullFace === value) {
  8899. return;
  8900. }
  8901. this._cullFace = value;
  8902. this._isCullFaceDirty = true;
  8903. },
  8904. enumerable: true,
  8905. configurable: true
  8906. });
  8907. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8908. get: function () {
  8909. return this._cull;
  8910. },
  8911. set: function (value) {
  8912. if (this._cull === value) {
  8913. return;
  8914. }
  8915. this._cull = value;
  8916. this._isCullDirty = true;
  8917. },
  8918. enumerable: true,
  8919. configurable: true
  8920. });
  8921. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8922. get: function () {
  8923. return this._depthFunc;
  8924. },
  8925. set: function (value) {
  8926. if (this._depthFunc === value) {
  8927. return;
  8928. }
  8929. this._depthFunc = value;
  8930. this._isDepthFuncDirty = true;
  8931. },
  8932. enumerable: true,
  8933. configurable: true
  8934. });
  8935. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8936. get: function () {
  8937. return this._depthMask;
  8938. },
  8939. set: function (value) {
  8940. if (this._depthMask === value) {
  8941. return;
  8942. }
  8943. this._depthMask = value;
  8944. this._isDepthMaskDirty = true;
  8945. },
  8946. enumerable: true,
  8947. configurable: true
  8948. });
  8949. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8950. get: function () {
  8951. return this._depthTest;
  8952. },
  8953. set: function (value) {
  8954. if (this._depthTest === value) {
  8955. return;
  8956. }
  8957. this._depthTest = value;
  8958. this._isDepthTestDirty = true;
  8959. },
  8960. enumerable: true,
  8961. configurable: true
  8962. });
  8963. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8964. get: function () {
  8965. return this._frontFace;
  8966. },
  8967. set: function (value) {
  8968. if (this._frontFace === value) {
  8969. return;
  8970. }
  8971. this._frontFace = value;
  8972. this._isFrontFaceDirty = true;
  8973. },
  8974. enumerable: true,
  8975. configurable: true
  8976. });
  8977. _DepthCullingState.prototype.reset = function () {
  8978. this._depthMask = true;
  8979. this._depthTest = true;
  8980. this._depthFunc = null;
  8981. this._cullFace = null;
  8982. this._cull = null;
  8983. this._zOffset = 0;
  8984. this._frontFace = null;
  8985. this._isDepthTestDirty = true;
  8986. this._isDepthMaskDirty = true;
  8987. this._isDepthFuncDirty = false;
  8988. this._isCullFaceDirty = false;
  8989. this._isCullDirty = false;
  8990. this._isZOffsetDirty = false;
  8991. this._isFrontFaceDirty = false;
  8992. };
  8993. _DepthCullingState.prototype.apply = function (gl) {
  8994. if (!this.isDirty) {
  8995. return;
  8996. }
  8997. // Cull
  8998. if (this._isCullDirty) {
  8999. if (this.cull) {
  9000. gl.enable(gl.CULL_FACE);
  9001. }
  9002. else {
  9003. gl.disable(gl.CULL_FACE);
  9004. }
  9005. this._isCullDirty = false;
  9006. }
  9007. // Cull face
  9008. if (this._isCullFaceDirty) {
  9009. gl.cullFace(this.cullFace);
  9010. this._isCullFaceDirty = false;
  9011. }
  9012. // Depth mask
  9013. if (this._isDepthMaskDirty) {
  9014. gl.depthMask(this.depthMask);
  9015. this._isDepthMaskDirty = false;
  9016. }
  9017. // Depth test
  9018. if (this._isDepthTestDirty) {
  9019. if (this.depthTest) {
  9020. gl.enable(gl.DEPTH_TEST);
  9021. }
  9022. else {
  9023. gl.disable(gl.DEPTH_TEST);
  9024. }
  9025. this._isDepthTestDirty = false;
  9026. }
  9027. // Depth func
  9028. if (this._isDepthFuncDirty) {
  9029. gl.depthFunc(this.depthFunc);
  9030. this._isDepthFuncDirty = false;
  9031. }
  9032. // zOffset
  9033. if (this._isZOffsetDirty) {
  9034. if (this.zOffset) {
  9035. gl.enable(gl.POLYGON_OFFSET_FILL);
  9036. gl.polygonOffset(this.zOffset, 0);
  9037. }
  9038. else {
  9039. gl.disable(gl.POLYGON_OFFSET_FILL);
  9040. }
  9041. this._isZOffsetDirty = false;
  9042. }
  9043. // Front face
  9044. if (this._isFrontFaceDirty) {
  9045. gl.frontFace(this.frontFace);
  9046. this._isFrontFaceDirty = false;
  9047. }
  9048. };
  9049. return _DepthCullingState;
  9050. }());
  9051. BABYLON._DepthCullingState = _DepthCullingState;
  9052. })(BABYLON || (BABYLON = {}));
  9053. //# sourceMappingURL=babylon.depthCullingState.js.map
  9054. var BABYLON;
  9055. (function (BABYLON) {
  9056. var _StencilState = /** @class */ (function () {
  9057. function _StencilState() {
  9058. this._isStencilTestDirty = false;
  9059. this._isStencilMaskDirty = false;
  9060. this._isStencilFuncDirty = false;
  9061. this._isStencilOpDirty = false;
  9062. this.reset();
  9063. }
  9064. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9065. get: function () {
  9066. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9072. get: function () {
  9073. return this._stencilFunc;
  9074. },
  9075. set: function (value) {
  9076. if (this._stencilFunc === value) {
  9077. return;
  9078. }
  9079. this._stencilFunc = value;
  9080. this._isStencilFuncDirty = true;
  9081. },
  9082. enumerable: true,
  9083. configurable: true
  9084. });
  9085. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9086. get: function () {
  9087. return this._stencilFuncRef;
  9088. },
  9089. set: function (value) {
  9090. if (this._stencilFuncRef === value) {
  9091. return;
  9092. }
  9093. this._stencilFuncRef = value;
  9094. this._isStencilFuncDirty = true;
  9095. },
  9096. enumerable: true,
  9097. configurable: true
  9098. });
  9099. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9100. get: function () {
  9101. return this._stencilFuncMask;
  9102. },
  9103. set: function (value) {
  9104. if (this._stencilFuncMask === value) {
  9105. return;
  9106. }
  9107. this._stencilFuncMask = value;
  9108. this._isStencilFuncDirty = true;
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9114. get: function () {
  9115. return this._stencilOpStencilFail;
  9116. },
  9117. set: function (value) {
  9118. if (this._stencilOpStencilFail === value) {
  9119. return;
  9120. }
  9121. this._stencilOpStencilFail = value;
  9122. this._isStencilOpDirty = true;
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9128. get: function () {
  9129. return this._stencilOpDepthFail;
  9130. },
  9131. set: function (value) {
  9132. if (this._stencilOpDepthFail === value) {
  9133. return;
  9134. }
  9135. this._stencilOpDepthFail = value;
  9136. this._isStencilOpDirty = true;
  9137. },
  9138. enumerable: true,
  9139. configurable: true
  9140. });
  9141. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9142. get: function () {
  9143. return this._stencilOpStencilDepthPass;
  9144. },
  9145. set: function (value) {
  9146. if (this._stencilOpStencilDepthPass === value) {
  9147. return;
  9148. }
  9149. this._stencilOpStencilDepthPass = value;
  9150. this._isStencilOpDirty = true;
  9151. },
  9152. enumerable: true,
  9153. configurable: true
  9154. });
  9155. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9156. get: function () {
  9157. return this._stencilMask;
  9158. },
  9159. set: function (value) {
  9160. if (this._stencilMask === value) {
  9161. return;
  9162. }
  9163. this._stencilMask = value;
  9164. this._isStencilMaskDirty = true;
  9165. },
  9166. enumerable: true,
  9167. configurable: true
  9168. });
  9169. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9170. get: function () {
  9171. return this._stencilTest;
  9172. },
  9173. set: function (value) {
  9174. if (this._stencilTest === value) {
  9175. return;
  9176. }
  9177. this._stencilTest = value;
  9178. this._isStencilTestDirty = true;
  9179. },
  9180. enumerable: true,
  9181. configurable: true
  9182. });
  9183. _StencilState.prototype.reset = function () {
  9184. this._stencilTest = false;
  9185. this._stencilMask = 0xFF;
  9186. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9187. this._stencilFuncRef = 1;
  9188. this._stencilFuncMask = 0xFF;
  9189. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9190. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9191. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9192. this._isStencilTestDirty = true;
  9193. this._isStencilMaskDirty = true;
  9194. this._isStencilFuncDirty = true;
  9195. this._isStencilOpDirty = true;
  9196. };
  9197. _StencilState.prototype.apply = function (gl) {
  9198. if (!this.isDirty) {
  9199. return;
  9200. }
  9201. // Stencil test
  9202. if (this._isStencilTestDirty) {
  9203. if (this.stencilTest) {
  9204. gl.enable(gl.STENCIL_TEST);
  9205. }
  9206. else {
  9207. gl.disable(gl.STENCIL_TEST);
  9208. }
  9209. this._isStencilTestDirty = false;
  9210. }
  9211. // Stencil mask
  9212. if (this._isStencilMaskDirty) {
  9213. gl.stencilMask(this.stencilMask);
  9214. this._isStencilMaskDirty = false;
  9215. }
  9216. // Stencil func
  9217. if (this._isStencilFuncDirty) {
  9218. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9219. this._isStencilFuncDirty = false;
  9220. }
  9221. // Stencil op
  9222. if (this._isStencilOpDirty) {
  9223. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9224. this._isStencilOpDirty = false;
  9225. }
  9226. };
  9227. return _StencilState;
  9228. }());
  9229. BABYLON._StencilState = _StencilState;
  9230. })(BABYLON || (BABYLON = {}));
  9231. //# sourceMappingURL=babylon.stencilState.js.map
  9232. var BABYLON;
  9233. (function (BABYLON) {
  9234. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9235. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9236. };
  9237. var compileRawShader = function (gl, source, type) {
  9238. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9239. gl.shaderSource(shader, source);
  9240. gl.compileShader(shader);
  9241. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9242. var log = gl.getShaderInfoLog(shader);
  9243. if (log) {
  9244. throw new Error(log);
  9245. }
  9246. }
  9247. if (!shader) {
  9248. throw new Error("Something went wrong while compile the shader.");
  9249. }
  9250. return shader;
  9251. };
  9252. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9253. var magFilter = gl.NEAREST;
  9254. var minFilter = gl.NEAREST;
  9255. switch (samplingMode) {
  9256. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9257. magFilter = gl.LINEAR;
  9258. if (generateMipMaps) {
  9259. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9260. }
  9261. else {
  9262. minFilter = gl.LINEAR;
  9263. }
  9264. break;
  9265. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9266. magFilter = gl.LINEAR;
  9267. if (generateMipMaps) {
  9268. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9269. }
  9270. else {
  9271. minFilter = gl.LINEAR;
  9272. }
  9273. break;
  9274. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9275. magFilter = gl.NEAREST;
  9276. if (generateMipMaps) {
  9277. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9278. }
  9279. else {
  9280. minFilter = gl.NEAREST;
  9281. }
  9282. break;
  9283. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9284. magFilter = gl.NEAREST;
  9285. if (generateMipMaps) {
  9286. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9287. }
  9288. else {
  9289. minFilter = gl.NEAREST;
  9290. }
  9291. break;
  9292. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9293. magFilter = gl.NEAREST;
  9294. if (generateMipMaps) {
  9295. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9296. }
  9297. else {
  9298. minFilter = gl.LINEAR;
  9299. }
  9300. break;
  9301. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9302. magFilter = gl.NEAREST;
  9303. if (generateMipMaps) {
  9304. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9305. }
  9306. else {
  9307. minFilter = gl.LINEAR;
  9308. }
  9309. break;
  9310. case BABYLON.Texture.NEAREST_LINEAR:
  9311. magFilter = gl.NEAREST;
  9312. minFilter = gl.LINEAR;
  9313. break;
  9314. case BABYLON.Texture.NEAREST_NEAREST:
  9315. magFilter = gl.NEAREST;
  9316. minFilter = gl.NEAREST;
  9317. break;
  9318. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9319. magFilter = gl.LINEAR;
  9320. if (generateMipMaps) {
  9321. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9322. }
  9323. else {
  9324. minFilter = gl.NEAREST;
  9325. }
  9326. break;
  9327. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9328. magFilter = gl.LINEAR;
  9329. if (generateMipMaps) {
  9330. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9331. }
  9332. else {
  9333. minFilter = gl.NEAREST;
  9334. }
  9335. break;
  9336. case BABYLON.Texture.LINEAR_LINEAR:
  9337. magFilter = gl.LINEAR;
  9338. minFilter = gl.LINEAR;
  9339. break;
  9340. case BABYLON.Texture.LINEAR_NEAREST:
  9341. magFilter = gl.LINEAR;
  9342. minFilter = gl.NEAREST;
  9343. break;
  9344. }
  9345. return {
  9346. min: minFilter,
  9347. mag: magFilter
  9348. };
  9349. };
  9350. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9351. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9352. var img;
  9353. var onload = function () {
  9354. loadedImages[index] = img;
  9355. loadedImages._internalCount++;
  9356. if (scene) {
  9357. scene._removePendingData(img);
  9358. }
  9359. if (loadedImages._internalCount === 6) {
  9360. onfinish(loadedImages);
  9361. }
  9362. };
  9363. var onerror = function (message, exception) {
  9364. if (scene) {
  9365. scene._removePendingData(img);
  9366. }
  9367. if (onErrorCallBack) {
  9368. onErrorCallBack(message, exception);
  9369. }
  9370. };
  9371. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9372. if (scene) {
  9373. scene._addPendingData(img);
  9374. }
  9375. };
  9376. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9377. if (onError === void 0) { onError = null; }
  9378. var loadedImages = [];
  9379. loadedImages._internalCount = 0;
  9380. for (var index = 0; index < 6; index++) {
  9381. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9382. }
  9383. };
  9384. var BufferPointer = /** @class */ (function () {
  9385. function BufferPointer() {
  9386. }
  9387. return BufferPointer;
  9388. }());
  9389. var InstancingAttributeInfo = /** @class */ (function () {
  9390. function InstancingAttributeInfo() {
  9391. }
  9392. return InstancingAttributeInfo;
  9393. }());
  9394. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9395. /**
  9396. * Define options used to create a render target texture
  9397. */
  9398. var RenderTargetCreationOptions = /** @class */ (function () {
  9399. function RenderTargetCreationOptions() {
  9400. }
  9401. return RenderTargetCreationOptions;
  9402. }());
  9403. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9404. /**
  9405. * Regroup several parameters relative to the browser in use
  9406. */
  9407. var EngineCapabilities = /** @class */ (function () {
  9408. function EngineCapabilities() {
  9409. }
  9410. return EngineCapabilities;
  9411. }());
  9412. BABYLON.EngineCapabilities = EngineCapabilities;
  9413. /**
  9414. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9415. */
  9416. var Engine = /** @class */ (function () {
  9417. /**
  9418. * @constructor
  9419. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9420. * @param antialias defines enable antialiasing (default: false)
  9421. * @param options defines further options to be sent to the getContext() function
  9422. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9423. */
  9424. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9425. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9426. var _this = this;
  9427. // Public members
  9428. this.forcePOTTextures = false;
  9429. this.isFullscreen = false;
  9430. this.isPointerLock = false;
  9431. this.cullBackFaces = true;
  9432. this.renderEvenInBackground = true;
  9433. this.preventCacheWipeBetweenFrames = false;
  9434. // To enable/disable IDB support and avoid XHR on .manifest
  9435. this.enableOfflineSupport = false;
  9436. this.scenes = new Array();
  9437. this.postProcesses = new Array();
  9438. // Observables
  9439. /**
  9440. * Observable event triggered each time the rendering canvas is resized
  9441. */
  9442. this.onResizeObservable = new BABYLON.Observable();
  9443. /**
  9444. * Observable event triggered each time the canvas loses focus
  9445. */
  9446. this.onCanvasBlurObservable = new BABYLON.Observable();
  9447. /**
  9448. * Observable event triggered each time the canvas gains focus
  9449. */
  9450. this.onCanvasFocusObservable = new BABYLON.Observable();
  9451. /**
  9452. * Observable event triggered each time the canvas receives pointerout event
  9453. */
  9454. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9455. /**
  9456. * Observable event triggered before each texture is initialized
  9457. */
  9458. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9459. //WebVR
  9460. this._vrDisplay = undefined;
  9461. this._vrSupported = false;
  9462. this._vrExclusivePointerMode = false;
  9463. // Uniform buffers list
  9464. this.disableUniformBuffers = false;
  9465. this._uniformBuffers = new Array();
  9466. // Observables
  9467. /**
  9468. * Observable raised when the engine begins a new frame
  9469. */
  9470. this.onBeginFrameObservable = new BABYLON.Observable();
  9471. /**
  9472. * Observable raised when the engine ends the current frame
  9473. */
  9474. this.onEndFrameObservable = new BABYLON.Observable();
  9475. /**
  9476. * Observable raised when the engine is about to compile a shader
  9477. */
  9478. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9479. /**
  9480. * Observable raised when the engine has jsut compiled a shader
  9481. */
  9482. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9483. this._windowIsBackground = false;
  9484. this._webGLVersion = 1.0;
  9485. this._badOS = false;
  9486. this._badDesktopOS = false;
  9487. /**
  9488. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9489. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9490. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9491. */
  9492. this.disableTextureBindingOptimization = false;
  9493. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9494. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9495. this.onVRRequestPresentStart = new BABYLON.Observable();
  9496. this._colorWrite = true;
  9497. this._drawCalls = new BABYLON.PerfCounter();
  9498. this._textureCollisions = new BABYLON.PerfCounter();
  9499. this._renderingQueueLaunched = false;
  9500. this._activeRenderLoops = new Array();
  9501. // Deterministic lockstepMaxSteps
  9502. this._deterministicLockstep = false;
  9503. this._lockstepMaxSteps = 4;
  9504. // Lost context
  9505. this.onContextLostObservable = new BABYLON.Observable();
  9506. this.onContextRestoredObservable = new BABYLON.Observable();
  9507. this._contextWasLost = false;
  9508. this._doNotHandleContextLost = false;
  9509. // FPS
  9510. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9511. this._fps = 60;
  9512. this._deltaTime = 0;
  9513. /**
  9514. * Turn this value on if you want to pause FPS computation when in background
  9515. */
  9516. this.disablePerformanceMonitorInBackground = false;
  9517. // States
  9518. this._depthCullingState = new BABYLON._DepthCullingState();
  9519. this._stencilState = new BABYLON._StencilState();
  9520. this._alphaState = new BABYLON._AlphaState();
  9521. this._alphaMode = Engine.ALPHA_DISABLE;
  9522. // Cache
  9523. this._internalTexturesCache = new Array();
  9524. this._activeChannel = 0;
  9525. this._currentTextureChannel = -1;
  9526. this._boundTexturesCache = {};
  9527. this._compiledEffects = {};
  9528. this._vertexAttribArraysEnabled = [];
  9529. this._uintIndicesCurrentlySet = false;
  9530. this._currentBoundBuffer = new Array();
  9531. this._currentBufferPointers = new Array();
  9532. this._currentInstanceLocations = new Array();
  9533. this._currentInstanceBuffers = new Array();
  9534. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9535. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9536. this._vaoRecordInProgress = false;
  9537. this._mustWipeVertexAttributes = false;
  9538. this._nextFreeTextureSlots = new Array();
  9539. this._maxSimultaneousTextures = 0;
  9540. this._activeRequests = new Array();
  9541. // Hardware supported Compressed Textures
  9542. this._texturesSupported = new Array();
  9543. this._onVRFullScreenTriggered = function () {
  9544. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9545. //get the old size before we change
  9546. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9547. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9548. //get the width and height, change the render size
  9549. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9550. _this.setHardwareScalingLevel(1);
  9551. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9552. }
  9553. else {
  9554. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9555. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9556. }
  9557. };
  9558. this._boundUniforms = {};
  9559. // Register promises
  9560. BABYLON.PromisePolyfill.Apply();
  9561. var canvas = null;
  9562. Engine.Instances.push(this);
  9563. if (!canvasOrContext) {
  9564. return;
  9565. }
  9566. options = options || {};
  9567. if (canvasOrContext.getContext) {
  9568. canvas = canvasOrContext;
  9569. this._renderingCanvas = canvas;
  9570. if (antialias != null) {
  9571. options.antialias = antialias;
  9572. }
  9573. if (options.deterministicLockstep === undefined) {
  9574. options.deterministicLockstep = false;
  9575. }
  9576. if (options.lockstepMaxSteps === undefined) {
  9577. options.lockstepMaxSteps = 4;
  9578. }
  9579. if (options.preserveDrawingBuffer === undefined) {
  9580. options.preserveDrawingBuffer = false;
  9581. }
  9582. if (options.audioEngine === undefined) {
  9583. options.audioEngine = true;
  9584. }
  9585. if (options.stencil === undefined) {
  9586. options.stencil = true;
  9587. }
  9588. this._deterministicLockstep = options.deterministicLockstep;
  9589. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9590. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9591. // Exceptions
  9592. if (navigator && navigator.userAgent) {
  9593. var ua = navigator.userAgent;
  9594. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9595. var exception = _a[_i];
  9596. var key = exception.key;
  9597. var targets = exception.targets;
  9598. if (ua.indexOf(key) > -1) {
  9599. if (exception.capture && exception.captureConstraint) {
  9600. var capture = exception.capture;
  9601. var constraint = exception.captureConstraint;
  9602. var regex = new RegExp(capture);
  9603. var matches = regex.exec(ua);
  9604. if (matches && matches.length > 0) {
  9605. var capturedValue = parseInt(matches[matches.length - 1]);
  9606. if (capturedValue >= constraint) {
  9607. continue;
  9608. }
  9609. }
  9610. }
  9611. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9612. var target = targets_1[_b];
  9613. switch (target) {
  9614. case "uniformBuffer":
  9615. this.disableUniformBuffers = true;
  9616. break;
  9617. case "textureBindingOptimization":
  9618. this.disableTextureBindingOptimization = true;
  9619. break;
  9620. }
  9621. }
  9622. break;
  9623. }
  9624. }
  9625. }
  9626. // GL
  9627. if (!options.disableWebGL2Support) {
  9628. try {
  9629. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9630. if (this._gl) {
  9631. this._webGLVersion = 2.0;
  9632. }
  9633. }
  9634. catch (e) {
  9635. // Do nothing
  9636. }
  9637. }
  9638. if (!this._gl) {
  9639. if (!canvas) {
  9640. throw new Error("The provided canvas is null or undefined.");
  9641. }
  9642. try {
  9643. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9644. }
  9645. catch (e) {
  9646. throw new Error("WebGL not supported");
  9647. }
  9648. }
  9649. if (!this._gl) {
  9650. throw new Error("WebGL not supported");
  9651. }
  9652. this._onCanvasFocus = function () {
  9653. _this.onCanvasFocusObservable.notifyObservers(_this);
  9654. };
  9655. this._onCanvasBlur = function () {
  9656. _this.onCanvasBlurObservable.notifyObservers(_this);
  9657. };
  9658. canvas.addEventListener("focus", this._onCanvasFocus);
  9659. canvas.addEventListener("blur", this._onCanvasBlur);
  9660. this._onBlur = function () {
  9661. if (_this.disablePerformanceMonitorInBackground) {
  9662. _this._performanceMonitor.disable();
  9663. }
  9664. _this._windowIsBackground = true;
  9665. };
  9666. this._onFocus = function () {
  9667. if (_this.disablePerformanceMonitorInBackground) {
  9668. _this._performanceMonitor.enable();
  9669. }
  9670. _this._windowIsBackground = false;
  9671. };
  9672. this._onCanvasPointerOut = function () {
  9673. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9674. };
  9675. window.addEventListener("blur", this._onBlur);
  9676. window.addEventListener("focus", this._onFocus);
  9677. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9678. // Context lost
  9679. if (!this._doNotHandleContextLost) {
  9680. this._onContextLost = function (evt) {
  9681. evt.preventDefault();
  9682. _this._contextWasLost = true;
  9683. BABYLON.Tools.Warn("WebGL context lost.");
  9684. _this.onContextLostObservable.notifyObservers(_this);
  9685. };
  9686. this._onContextRestored = function (evt) {
  9687. // Adding a timeout to avoid race condition at browser level
  9688. setTimeout(function () {
  9689. // Rebuild gl context
  9690. _this._initGLContext();
  9691. // Rebuild effects
  9692. _this._rebuildEffects();
  9693. // Rebuild textures
  9694. _this._rebuildInternalTextures();
  9695. // Rebuild buffers
  9696. _this._rebuildBuffers();
  9697. // Cache
  9698. _this.wipeCaches(true);
  9699. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9700. _this.onContextRestoredObservable.notifyObservers(_this);
  9701. _this._contextWasLost = false;
  9702. }, 0);
  9703. };
  9704. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9705. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9706. }
  9707. }
  9708. else {
  9709. this._gl = canvasOrContext;
  9710. this._renderingCanvas = this._gl.canvas;
  9711. if (this._gl.renderbufferStorageMultisample) {
  9712. this._webGLVersion = 2.0;
  9713. }
  9714. options.stencil = this._gl.getContextAttributes().stencil;
  9715. }
  9716. // Viewport
  9717. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9718. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9719. this.resize();
  9720. this._isStencilEnable = options.stencil ? true : false;
  9721. this._initGLContext();
  9722. if (canvas) {
  9723. // Fullscreen
  9724. this._onFullscreenChange = function () {
  9725. if (document.fullscreen !== undefined) {
  9726. _this.isFullscreen = document.fullscreen;
  9727. }
  9728. else if (document.mozFullScreen !== undefined) {
  9729. _this.isFullscreen = document.mozFullScreen;
  9730. }
  9731. else if (document.webkitIsFullScreen !== undefined) {
  9732. _this.isFullscreen = document.webkitIsFullScreen;
  9733. }
  9734. else if (document.msIsFullScreen !== undefined) {
  9735. _this.isFullscreen = document.msIsFullScreen;
  9736. }
  9737. // Pointer lock
  9738. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9739. canvas.requestPointerLock = canvas.requestPointerLock ||
  9740. canvas.msRequestPointerLock ||
  9741. canvas.mozRequestPointerLock ||
  9742. canvas.webkitRequestPointerLock;
  9743. if (canvas.requestPointerLock) {
  9744. canvas.requestPointerLock();
  9745. }
  9746. }
  9747. };
  9748. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9749. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9750. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9751. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9752. // Pointer lock
  9753. this._onPointerLockChange = function () {
  9754. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9755. document.webkitPointerLockElement === canvas ||
  9756. document.msPointerLockElement === canvas ||
  9757. document.pointerLockElement === canvas);
  9758. };
  9759. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9760. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9761. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9762. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9763. this._onVRDisplayPointerRestricted = function () {
  9764. if (canvas) {
  9765. canvas.requestPointerLock();
  9766. }
  9767. };
  9768. this._onVRDisplayPointerUnrestricted = function () {
  9769. document.exitPointerLock();
  9770. };
  9771. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9772. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9773. }
  9774. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9775. Engine.audioEngine = new BABYLON.AudioEngine();
  9776. }
  9777. // Prepare buffer pointers
  9778. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9779. this._currentBufferPointers[i] = new BufferPointer();
  9780. }
  9781. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9782. // Load WebVR Devices
  9783. if (options.autoEnableWebVR) {
  9784. this.initWebVR();
  9785. }
  9786. // Detect if we are running on a faulty buggy OS.
  9787. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9788. // Detect if we are running on a faulty buggy desktop OS.
  9789. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9790. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9791. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9792. }
  9793. Object.defineProperty(Engine, "LastCreatedEngine", {
  9794. get: function () {
  9795. if (Engine.Instances.length === 0) {
  9796. return null;
  9797. }
  9798. return Engine.Instances[Engine.Instances.length - 1];
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. Object.defineProperty(Engine, "LastCreatedScene", {
  9804. get: function () {
  9805. var lastCreatedEngine = Engine.LastCreatedEngine;
  9806. if (!lastCreatedEngine) {
  9807. return null;
  9808. }
  9809. if (lastCreatedEngine.scenes.length === 0) {
  9810. return null;
  9811. }
  9812. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. /**
  9818. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9819. */
  9820. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9821. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9822. var engine = Engine.Instances[engineIndex];
  9823. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9824. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9825. }
  9826. }
  9827. };
  9828. Object.defineProperty(Engine, "NEVER", {
  9829. get: function () {
  9830. return Engine._NEVER;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. Object.defineProperty(Engine, "ALWAYS", {
  9836. get: function () {
  9837. return Engine._ALWAYS;
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Object.defineProperty(Engine, "LESS", {
  9843. get: function () {
  9844. return Engine._LESS;
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Object.defineProperty(Engine, "EQUAL", {
  9850. get: function () {
  9851. return Engine._EQUAL;
  9852. },
  9853. enumerable: true,
  9854. configurable: true
  9855. });
  9856. Object.defineProperty(Engine, "LEQUAL", {
  9857. get: function () {
  9858. return Engine._LEQUAL;
  9859. },
  9860. enumerable: true,
  9861. configurable: true
  9862. });
  9863. Object.defineProperty(Engine, "GREATER", {
  9864. get: function () {
  9865. return Engine._GREATER;
  9866. },
  9867. enumerable: true,
  9868. configurable: true
  9869. });
  9870. Object.defineProperty(Engine, "GEQUAL", {
  9871. get: function () {
  9872. return Engine._GEQUAL;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(Engine, "NOTEQUAL", {
  9878. get: function () {
  9879. return Engine._NOTEQUAL;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Engine, "KEEP", {
  9885. get: function () {
  9886. return Engine._KEEP;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(Engine, "REPLACE", {
  9892. get: function () {
  9893. return Engine._REPLACE;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Object.defineProperty(Engine, "INCR", {
  9899. get: function () {
  9900. return Engine._INCR;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(Engine, "DECR", {
  9906. get: function () {
  9907. return Engine._DECR;
  9908. },
  9909. enumerable: true,
  9910. configurable: true
  9911. });
  9912. Object.defineProperty(Engine, "INVERT", {
  9913. get: function () {
  9914. return Engine._INVERT;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(Engine, "INCR_WRAP", {
  9920. get: function () {
  9921. return Engine._INCR_WRAP;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(Engine, "DECR_WRAP", {
  9927. get: function () {
  9928. return Engine._DECR_WRAP;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9934. get: function () {
  9935. return Engine._ALPHA_DISABLE;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9941. get: function () {
  9942. return Engine._ALPHA_ONEONE;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. Object.defineProperty(Engine, "ALPHA_ADD", {
  9948. get: function () {
  9949. return Engine._ALPHA_ADD;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9955. get: function () {
  9956. return Engine._ALPHA_COMBINE;
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9962. get: function () {
  9963. return Engine._ALPHA_SUBTRACT;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9969. get: function () {
  9970. return Engine._ALPHA_MULTIPLY;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9976. get: function () {
  9977. return Engine._ALPHA_MAXIMIZED;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9983. get: function () {
  9984. return Engine._ALPHA_PREMULTIPLIED;
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9990. get: function () {
  9991. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9997. get: function () {
  9998. return Engine._ALPHA_INTERPOLATE;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10004. get: function () {
  10005. return Engine._ALPHA_SCREENMODE;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10011. get: function () {
  10012. return Engine._DELAYLOADSTATE_NONE;
  10013. },
  10014. enumerable: true,
  10015. configurable: true
  10016. });
  10017. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10018. get: function () {
  10019. return Engine._DELAYLOADSTATE_LOADED;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10025. get: function () {
  10026. return Engine._DELAYLOADSTATE_LOADING;
  10027. },
  10028. enumerable: true,
  10029. configurable: true
  10030. });
  10031. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10032. get: function () {
  10033. return Engine._DELAYLOADSTATE_NOTLOADED;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10039. get: function () {
  10040. return Engine._TEXTUREFORMAT_ALPHA;
  10041. },
  10042. enumerable: true,
  10043. configurable: true
  10044. });
  10045. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10046. get: function () {
  10047. return Engine._TEXTUREFORMAT_LUMINANCE;
  10048. },
  10049. enumerable: true,
  10050. configurable: true
  10051. });
  10052. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10053. get: function () {
  10054. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10055. },
  10056. enumerable: true,
  10057. configurable: true
  10058. });
  10059. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10060. get: function () {
  10061. return Engine._TEXTUREFORMAT_RGB;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10067. get: function () {
  10068. return Engine._TEXTUREFORMAT_RGBA;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10074. get: function () {
  10075. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10081. get: function () {
  10082. return Engine._TEXTURETYPE_FLOAT;
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10088. get: function () {
  10089. return Engine._TEXTURETYPE_HALF_FLOAT;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10095. get: function () {
  10096. return Engine._SCALEMODE_FLOOR;
  10097. },
  10098. enumerable: true,
  10099. configurable: true
  10100. });
  10101. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10102. get: function () {
  10103. return Engine._SCALEMODE_NEAREST;
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10109. get: function () {
  10110. return Engine._SCALEMODE_CEILING;
  10111. },
  10112. enumerable: true,
  10113. configurable: true
  10114. });
  10115. Object.defineProperty(Engine, "Version", {
  10116. get: function () {
  10117. return "3.2.0-alpha6";
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10123. get: function () {
  10124. return this._vrExclusivePointerMode;
  10125. },
  10126. enumerable: true,
  10127. configurable: true
  10128. });
  10129. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10130. get: function () {
  10131. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10137. get: function () {
  10138. return this._webGLVersion < 2 || this.forcePOTTextures;
  10139. },
  10140. enumerable: true,
  10141. configurable: true
  10142. });
  10143. Object.defineProperty(Engine.prototype, "badOS", {
  10144. get: function () {
  10145. return this._badOS;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10151. get: function () {
  10152. return this._badDesktopOS;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10158. get: function () {
  10159. return this._performanceMonitor;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10165. get: function () {
  10166. return this._texturesSupported;
  10167. },
  10168. enumerable: true,
  10169. configurable: true
  10170. });
  10171. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10172. get: function () {
  10173. return this._textureFormatInUse;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(Engine.prototype, "currentViewport", {
  10179. get: function () {
  10180. return this._cachedViewport;
  10181. },
  10182. enumerable: true,
  10183. configurable: true
  10184. });
  10185. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10186. // Empty texture
  10187. get: function () {
  10188. if (!this._emptyTexture) {
  10189. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10190. }
  10191. return this._emptyTexture;
  10192. },
  10193. enumerable: true,
  10194. configurable: true
  10195. });
  10196. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10197. get: function () {
  10198. if (!this._emptyTexture3D) {
  10199. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10200. }
  10201. return this._emptyTexture3D;
  10202. },
  10203. enumerable: true,
  10204. configurable: true
  10205. });
  10206. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10207. get: function () {
  10208. if (!this._emptyCubeTexture) {
  10209. var faceData = new Uint8Array(4);
  10210. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10211. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10212. }
  10213. return this._emptyCubeTexture;
  10214. },
  10215. enumerable: true,
  10216. configurable: true
  10217. });
  10218. Engine.prototype._rebuildInternalTextures = function () {
  10219. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10220. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10221. var internalTexture = currentState_1[_i];
  10222. internalTexture._rebuild();
  10223. }
  10224. };
  10225. Engine.prototype._rebuildEffects = function () {
  10226. for (var key in this._compiledEffects) {
  10227. var effect = this._compiledEffects[key];
  10228. effect._prepareEffect();
  10229. }
  10230. BABYLON.Effect.ResetCache();
  10231. };
  10232. Engine.prototype._rebuildBuffers = function () {
  10233. // Index / Vertex
  10234. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10235. var scene = _a[_i];
  10236. scene.resetCachedMaterial();
  10237. scene._rebuildGeometries();
  10238. scene._rebuildTextures();
  10239. }
  10240. // Uniforms
  10241. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10242. var uniformBuffer = _c[_b];
  10243. uniformBuffer._rebuild();
  10244. }
  10245. };
  10246. Engine.prototype._initGLContext = function () {
  10247. // Caps
  10248. this._caps = new EngineCapabilities();
  10249. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10250. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10251. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10252. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10253. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10254. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10255. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10256. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10257. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10258. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10259. // Infos
  10260. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10261. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10262. if (rendererInfo != null) {
  10263. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10264. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10265. }
  10266. if (!this._glVendor) {
  10267. this._glVendor = "Unknown vendor";
  10268. }
  10269. if (!this._glRenderer) {
  10270. this._glRenderer = "Unknown renderer";
  10271. }
  10272. // Constants
  10273. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10274. if (this._gl.RGBA16F !== 0x881A) {
  10275. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10276. }
  10277. if (this._gl.RGBA32F !== 0x8814) {
  10278. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10279. }
  10280. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10281. this._gl.DEPTH24_STENCIL8 = 35056;
  10282. }
  10283. // Extensions
  10284. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10285. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10286. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10287. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10288. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10289. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10290. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10291. 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');
  10292. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10293. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10294. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10295. this._caps.highPrecisionShaderSupported = true;
  10296. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10297. if (this._caps.timerQuery) {
  10298. if (this._webGLVersion === 1) {
  10299. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10300. }
  10301. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10302. }
  10303. // Checks if some of the format renders first to allow the use of webgl inspector.
  10304. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10305. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10306. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10307. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10308. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10309. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10310. if (this._webGLVersion > 1) {
  10311. this._gl.HALF_FLOAT_OES = 0x140B;
  10312. }
  10313. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10314. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10315. // Draw buffers
  10316. if (this._webGLVersion > 1) {
  10317. this._caps.drawBuffersExtension = true;
  10318. }
  10319. else {
  10320. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10321. if (drawBuffersExtension !== null) {
  10322. this._caps.drawBuffersExtension = true;
  10323. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10324. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10325. for (var i = 0; i < 16; i++) {
  10326. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10327. }
  10328. }
  10329. else {
  10330. this._caps.drawBuffersExtension = false;
  10331. }
  10332. }
  10333. // Depth Texture
  10334. if (this._webGLVersion > 1) {
  10335. this._caps.depthTextureExtension = true;
  10336. }
  10337. else {
  10338. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10339. if (depthTextureExtension != null) {
  10340. this._caps.depthTextureExtension = true;
  10341. }
  10342. }
  10343. // Vertex array object
  10344. if (this._webGLVersion > 1) {
  10345. this._caps.vertexArrayObject = true;
  10346. }
  10347. else {
  10348. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10349. if (vertexArrayObjectExtension != null) {
  10350. this._caps.vertexArrayObject = true;
  10351. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10352. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10353. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10354. }
  10355. else {
  10356. this._caps.vertexArrayObject = false;
  10357. }
  10358. }
  10359. // Instances count
  10360. if (this._webGLVersion > 1) {
  10361. this._caps.instancedArrays = true;
  10362. }
  10363. else {
  10364. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10365. if (instanceExtension != null) {
  10366. this._caps.instancedArrays = true;
  10367. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10368. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10369. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10370. }
  10371. else {
  10372. this._caps.instancedArrays = false;
  10373. }
  10374. }
  10375. // Intelligently add supported compressed formats in order to check for.
  10376. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10377. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10378. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10379. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10380. if (this._caps.astc)
  10381. this.texturesSupported.push('-astc.ktx');
  10382. if (this._caps.s3tc)
  10383. this.texturesSupported.push('-dxt.ktx');
  10384. if (this._caps.pvrtc)
  10385. this.texturesSupported.push('-pvrtc.ktx');
  10386. if (this._caps.etc2)
  10387. this.texturesSupported.push('-etc2.ktx');
  10388. if (this._caps.etc1)
  10389. this.texturesSupported.push('-etc1.ktx');
  10390. if (this._gl.getShaderPrecisionFormat) {
  10391. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10392. if (highp) {
  10393. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10394. }
  10395. }
  10396. // Depth buffer
  10397. this.setDepthBuffer(true);
  10398. this.setDepthFunctionToLessOrEqual();
  10399. this.setDepthWrite(true);
  10400. // Texture maps
  10401. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10402. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10403. this._nextFreeTextureSlots.push(slot);
  10404. }
  10405. };
  10406. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10407. get: function () {
  10408. return this._webGLVersion;
  10409. },
  10410. enumerable: true,
  10411. configurable: true
  10412. });
  10413. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10414. /**
  10415. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10416. */
  10417. get: function () {
  10418. return this._isStencilEnable;
  10419. },
  10420. enumerable: true,
  10421. configurable: true
  10422. });
  10423. Engine.prototype._prepareWorkingCanvas = function () {
  10424. if (this._workingCanvas) {
  10425. return;
  10426. }
  10427. this._workingCanvas = document.createElement("canvas");
  10428. var context = this._workingCanvas.getContext("2d");
  10429. if (context) {
  10430. this._workingContext = context;
  10431. }
  10432. };
  10433. Engine.prototype.resetTextureCache = function () {
  10434. for (var key in this._boundTexturesCache) {
  10435. var boundTexture = this._boundTexturesCache[key];
  10436. if (boundTexture) {
  10437. this._removeDesignatedSlot(boundTexture);
  10438. }
  10439. this._boundTexturesCache[key] = null;
  10440. }
  10441. if (!this.disableTextureBindingOptimization) {
  10442. this._nextFreeTextureSlots = [];
  10443. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10444. this._nextFreeTextureSlots.push(slot);
  10445. }
  10446. }
  10447. this._currentTextureChannel = -1;
  10448. };
  10449. Engine.prototype.isDeterministicLockStep = function () {
  10450. return this._deterministicLockstep;
  10451. };
  10452. Engine.prototype.getLockstepMaxSteps = function () {
  10453. return this._lockstepMaxSteps;
  10454. };
  10455. Engine.prototype.getGlInfo = function () {
  10456. return {
  10457. vendor: this._glVendor,
  10458. renderer: this._glRenderer,
  10459. version: this._glVersion
  10460. };
  10461. };
  10462. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10463. if (useScreen === void 0) { useScreen = false; }
  10464. var viewport = camera.viewport;
  10465. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10466. };
  10467. Engine.prototype.getRenderWidth = function (useScreen) {
  10468. if (useScreen === void 0) { useScreen = false; }
  10469. if (!useScreen && this._currentRenderTarget) {
  10470. return this._currentRenderTarget.width;
  10471. }
  10472. return this._gl.drawingBufferWidth;
  10473. };
  10474. Engine.prototype.getRenderHeight = function (useScreen) {
  10475. if (useScreen === void 0) { useScreen = false; }
  10476. if (!useScreen && this._currentRenderTarget) {
  10477. return this._currentRenderTarget.height;
  10478. }
  10479. return this._gl.drawingBufferHeight;
  10480. };
  10481. Engine.prototype.getRenderingCanvas = function () {
  10482. return this._renderingCanvas;
  10483. };
  10484. Engine.prototype.getRenderingCanvasClientRect = function () {
  10485. if (!this._renderingCanvas) {
  10486. return null;
  10487. }
  10488. return this._renderingCanvas.getBoundingClientRect();
  10489. };
  10490. Engine.prototype.setHardwareScalingLevel = function (level) {
  10491. this._hardwareScalingLevel = level;
  10492. this.resize();
  10493. };
  10494. Engine.prototype.getHardwareScalingLevel = function () {
  10495. return this._hardwareScalingLevel;
  10496. };
  10497. Engine.prototype.getLoadedTexturesCache = function () {
  10498. return this._internalTexturesCache;
  10499. };
  10500. Engine.prototype.getCaps = function () {
  10501. return this._caps;
  10502. };
  10503. Object.defineProperty(Engine.prototype, "drawCalls", {
  10504. /** The number of draw calls submitted last frame */
  10505. get: function () {
  10506. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10507. return 0;
  10508. },
  10509. enumerable: true,
  10510. configurable: true
  10511. });
  10512. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10513. get: function () {
  10514. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10515. return null;
  10516. },
  10517. enumerable: true,
  10518. configurable: true
  10519. });
  10520. Engine.prototype.getDepthFunction = function () {
  10521. return this._depthCullingState.depthFunc;
  10522. };
  10523. Engine.prototype.setDepthFunction = function (depthFunc) {
  10524. this._depthCullingState.depthFunc = depthFunc;
  10525. };
  10526. Engine.prototype.setDepthFunctionToGreater = function () {
  10527. this._depthCullingState.depthFunc = this._gl.GREATER;
  10528. };
  10529. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10530. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10531. };
  10532. Engine.prototype.setDepthFunctionToLess = function () {
  10533. this._depthCullingState.depthFunc = this._gl.LESS;
  10534. };
  10535. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10536. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10537. };
  10538. Engine.prototype.getStencilBuffer = function () {
  10539. return this._stencilState.stencilTest;
  10540. };
  10541. Engine.prototype.setStencilBuffer = function (enable) {
  10542. this._stencilState.stencilTest = enable;
  10543. };
  10544. Engine.prototype.getStencilMask = function () {
  10545. return this._stencilState.stencilMask;
  10546. };
  10547. Engine.prototype.setStencilMask = function (mask) {
  10548. this._stencilState.stencilMask = mask;
  10549. };
  10550. Engine.prototype.getStencilFunction = function () {
  10551. return this._stencilState.stencilFunc;
  10552. };
  10553. Engine.prototype.getStencilFunctionReference = function () {
  10554. return this._stencilState.stencilFuncRef;
  10555. };
  10556. Engine.prototype.getStencilFunctionMask = function () {
  10557. return this._stencilState.stencilFuncMask;
  10558. };
  10559. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10560. this._stencilState.stencilFunc = stencilFunc;
  10561. };
  10562. Engine.prototype.setStencilFunctionReference = function (reference) {
  10563. this._stencilState.stencilFuncRef = reference;
  10564. };
  10565. Engine.prototype.setStencilFunctionMask = function (mask) {
  10566. this._stencilState.stencilFuncMask = mask;
  10567. };
  10568. Engine.prototype.getStencilOperationFail = function () {
  10569. return this._stencilState.stencilOpStencilFail;
  10570. };
  10571. Engine.prototype.getStencilOperationDepthFail = function () {
  10572. return this._stencilState.stencilOpDepthFail;
  10573. };
  10574. Engine.prototype.getStencilOperationPass = function () {
  10575. return this._stencilState.stencilOpStencilDepthPass;
  10576. };
  10577. Engine.prototype.setStencilOperationFail = function (operation) {
  10578. this._stencilState.stencilOpStencilFail = operation;
  10579. };
  10580. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10581. this._stencilState.stencilOpDepthFail = operation;
  10582. };
  10583. Engine.prototype.setStencilOperationPass = function (operation) {
  10584. this._stencilState.stencilOpStencilDepthPass = operation;
  10585. };
  10586. Engine.prototype.setDitheringState = function (value) {
  10587. if (value) {
  10588. this._gl.enable(this._gl.DITHER);
  10589. }
  10590. else {
  10591. this._gl.disable(this._gl.DITHER);
  10592. }
  10593. };
  10594. Engine.prototype.setRasterizerState = function (value) {
  10595. if (value) {
  10596. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10597. }
  10598. else {
  10599. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10600. }
  10601. };
  10602. /**
  10603. * stop executing a render loop function and remove it from the execution array
  10604. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10605. */
  10606. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10607. if (!renderFunction) {
  10608. this._activeRenderLoops = [];
  10609. return;
  10610. }
  10611. var index = this._activeRenderLoops.indexOf(renderFunction);
  10612. if (index >= 0) {
  10613. this._activeRenderLoops.splice(index, 1);
  10614. }
  10615. };
  10616. Engine.prototype._renderLoop = function () {
  10617. if (!this._contextWasLost) {
  10618. var shouldRender = true;
  10619. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10620. shouldRender = false;
  10621. }
  10622. if (shouldRender) {
  10623. // Start new frame
  10624. this.beginFrame();
  10625. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10626. var renderFunction = this._activeRenderLoops[index];
  10627. renderFunction();
  10628. }
  10629. // Present
  10630. this.endFrame();
  10631. }
  10632. }
  10633. if (this._activeRenderLoops.length > 0) {
  10634. // Register new frame
  10635. var requester = null;
  10636. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10637. requester = this._vrDisplay;
  10638. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10639. }
  10640. else {
  10641. this._renderingQueueLaunched = false;
  10642. }
  10643. };
  10644. /**
  10645. * Register and execute a render loop. The engine can have more than one render function.
  10646. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10647. * @example
  10648. * engine.runRenderLoop(function () {
  10649. * scene.render()
  10650. * })
  10651. */
  10652. Engine.prototype.runRenderLoop = function (renderFunction) {
  10653. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10654. return;
  10655. }
  10656. this._activeRenderLoops.push(renderFunction);
  10657. if (!this._renderingQueueLaunched) {
  10658. this._renderingQueueLaunched = true;
  10659. this._bindedRenderFunction = this._renderLoop.bind(this);
  10660. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10661. }
  10662. };
  10663. /**
  10664. * Toggle full screen mode.
  10665. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10666. * @param {any} options - an options object to be sent to the requestFullscreen function
  10667. */
  10668. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10669. if (this.isFullscreen) {
  10670. BABYLON.Tools.ExitFullscreen();
  10671. }
  10672. else {
  10673. this._pointerLockRequested = requestPointerLock;
  10674. if (this._renderingCanvas) {
  10675. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10676. }
  10677. }
  10678. };
  10679. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10680. if (stencil === void 0) { stencil = false; }
  10681. this.applyStates();
  10682. var mode = 0;
  10683. if (backBuffer && color) {
  10684. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10685. mode |= this._gl.COLOR_BUFFER_BIT;
  10686. }
  10687. if (depth) {
  10688. this._gl.clearDepth(1.0);
  10689. mode |= this._gl.DEPTH_BUFFER_BIT;
  10690. }
  10691. if (stencil) {
  10692. this._gl.clearStencil(0);
  10693. mode |= this._gl.STENCIL_BUFFER_BIT;
  10694. }
  10695. this._gl.clear(mode);
  10696. };
  10697. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10698. var gl = this._gl;
  10699. // Save state
  10700. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10701. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10702. // Change state
  10703. gl.enable(gl.SCISSOR_TEST);
  10704. gl.scissor(x, y, width, height);
  10705. // Clear
  10706. this.clear(clearColor, true, true, true);
  10707. // Restore state
  10708. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10709. if (curScissor === true) {
  10710. gl.enable(gl.SCISSOR_TEST);
  10711. }
  10712. else {
  10713. gl.disable(gl.SCISSOR_TEST);
  10714. }
  10715. };
  10716. /**
  10717. * Set the WebGL's viewport
  10718. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10719. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10720. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10721. */
  10722. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10723. var width = requiredWidth || this.getRenderWidth();
  10724. var height = requiredHeight || this.getRenderHeight();
  10725. var x = viewport.x || 0;
  10726. var y = viewport.y || 0;
  10727. this._cachedViewport = viewport;
  10728. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10729. };
  10730. /**
  10731. * Directly set the WebGL Viewport
  10732. * The x, y, width & height are directly passed to the WebGL call
  10733. * @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.
  10734. */
  10735. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10736. var currentViewport = this._cachedViewport;
  10737. this._cachedViewport = null;
  10738. this._gl.viewport(x, y, width, height);
  10739. return currentViewport;
  10740. };
  10741. Engine.prototype.beginFrame = function () {
  10742. this.onBeginFrameObservable.notifyObservers(this);
  10743. this._measureFps();
  10744. };
  10745. Engine.prototype.endFrame = function () {
  10746. //force a flush in case we are using a bad OS.
  10747. if (this._badOS) {
  10748. this.flushFramebuffer();
  10749. }
  10750. //submit frame to the vr device, if enabled
  10751. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10752. // TODO: We should only submit the frame if we read frameData successfully.
  10753. this._vrDisplay.submitFrame();
  10754. }
  10755. this.onEndFrameObservable.notifyObservers(this);
  10756. };
  10757. /**
  10758. * resize the view according to the canvas' size.
  10759. * @example
  10760. * window.addEventListener("resize", function () {
  10761. * engine.resize();
  10762. * });
  10763. */
  10764. Engine.prototype.resize = function () {
  10765. // We're not resizing the size of the canvas while in VR mode & presenting
  10766. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10767. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10768. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10769. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10770. }
  10771. };
  10772. /**
  10773. * force a specific size of the canvas
  10774. * @param {number} width - the new canvas' width
  10775. * @param {number} height - the new canvas' height
  10776. */
  10777. Engine.prototype.setSize = function (width, height) {
  10778. if (!this._renderingCanvas) {
  10779. return;
  10780. }
  10781. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10782. return;
  10783. }
  10784. this._renderingCanvas.width = width;
  10785. this._renderingCanvas.height = height;
  10786. for (var index = 0; index < this.scenes.length; index++) {
  10787. var scene = this.scenes[index];
  10788. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10789. var cam = scene.cameras[camIndex];
  10790. cam._currentRenderId = 0;
  10791. }
  10792. }
  10793. if (this.onResizeObservable.hasObservers) {
  10794. this.onResizeObservable.notifyObservers(this);
  10795. }
  10796. };
  10797. // WebVR functions
  10798. Engine.prototype.isVRDevicePresent = function () {
  10799. return !!this._vrDisplay;
  10800. };
  10801. Engine.prototype.getVRDevice = function () {
  10802. return this._vrDisplay;
  10803. };
  10804. Engine.prototype.initWebVR = function () {
  10805. var _this = this;
  10806. var notifyObservers = function () {
  10807. var eventArgs = {
  10808. vrDisplay: _this._vrDisplay,
  10809. vrSupported: _this._vrSupported
  10810. };
  10811. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10812. };
  10813. if (!this._onVrDisplayConnect) {
  10814. this._onVrDisplayConnect = function (event) {
  10815. _this._vrDisplay = event.display;
  10816. notifyObservers();
  10817. };
  10818. this._onVrDisplayDisconnect = function () {
  10819. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10820. _this._vrDisplay = undefined;
  10821. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10822. notifyObservers();
  10823. };
  10824. this._onVrDisplayPresentChange = function () {
  10825. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10826. };
  10827. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10828. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10829. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10830. }
  10831. this._getVRDisplays(notifyObservers);
  10832. return this.onVRDisplayChangedObservable;
  10833. };
  10834. Engine.prototype.enableVR = function () {
  10835. var _this = this;
  10836. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10837. var onResolved = function () {
  10838. _this.onVRRequestPresentComplete.notifyObservers(true);
  10839. _this._onVRFullScreenTriggered();
  10840. };
  10841. var onRejected = function () {
  10842. _this.onVRRequestPresentComplete.notifyObservers(false);
  10843. };
  10844. this.onVRRequestPresentStart.notifyObservers(this);
  10845. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10846. }
  10847. };
  10848. Engine.prototype.disableVR = function () {
  10849. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10850. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10851. }
  10852. };
  10853. Engine.prototype._getVRDisplays = function (callback) {
  10854. var _this = this;
  10855. var getWebVRDevices = function (devices) {
  10856. _this._vrSupported = true;
  10857. // note that devices may actually be an empty array. This is fine;
  10858. // we expect this._vrDisplay to be undefined in this case.
  10859. return _this._vrDisplay = devices[0];
  10860. };
  10861. if (navigator.getVRDisplays) {
  10862. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10863. // TODO: System CANNOT support WebVR, despite API presence.
  10864. _this._vrSupported = false;
  10865. callback();
  10866. });
  10867. }
  10868. else {
  10869. // TODO: Browser does not support WebVR
  10870. this._vrDisplay = undefined;
  10871. this._vrSupported = false;
  10872. callback();
  10873. }
  10874. };
  10875. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10876. if (this._currentRenderTarget) {
  10877. this.unBindFramebuffer(this._currentRenderTarget);
  10878. }
  10879. this._currentRenderTarget = texture;
  10880. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10881. var gl = this._gl;
  10882. if (texture.isCube) {
  10883. if (faceIndex === undefined) {
  10884. faceIndex = 0;
  10885. }
  10886. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10887. }
  10888. if (this._cachedViewport && !forceFullscreenViewport) {
  10889. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10890. }
  10891. else {
  10892. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10893. }
  10894. this.wipeCaches();
  10895. };
  10896. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10897. if (this._currentFramebuffer !== framebuffer) {
  10898. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10899. this._currentFramebuffer = framebuffer;
  10900. }
  10901. };
  10902. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10903. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10904. this._currentRenderTarget = null;
  10905. // If MSAA, we need to bitblt back to main texture
  10906. var gl = this._gl;
  10907. if (texture._MSAAFramebuffer) {
  10908. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10909. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10910. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10911. }
  10912. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10913. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10914. gl.generateMipmap(gl.TEXTURE_2D);
  10915. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10916. }
  10917. if (onBeforeUnbind) {
  10918. if (texture._MSAAFramebuffer) {
  10919. // Bind the correct framebuffer
  10920. this.bindUnboundFramebuffer(texture._framebuffer);
  10921. }
  10922. onBeforeUnbind();
  10923. }
  10924. this.bindUnboundFramebuffer(null);
  10925. };
  10926. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10927. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10928. this._currentRenderTarget = null;
  10929. // If MSAA, we need to bitblt back to main texture
  10930. var gl = this._gl;
  10931. if (textures[0]._MSAAFramebuffer) {
  10932. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10933. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10934. var attachments = textures[0]._attachments;
  10935. if (!attachments) {
  10936. attachments = new Array(textures.length);
  10937. textures[0]._attachments = attachments;
  10938. }
  10939. for (var i = 0; i < textures.length; i++) {
  10940. var texture = textures[i];
  10941. for (var j = 0; j < attachments.length; j++) {
  10942. attachments[j] = gl.NONE;
  10943. }
  10944. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10945. gl.readBuffer(attachments[i]);
  10946. gl.drawBuffers(attachments);
  10947. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10948. }
  10949. for (var i = 0; i < attachments.length; i++) {
  10950. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10951. }
  10952. gl.drawBuffers(attachments);
  10953. }
  10954. for (var i = 0; i < textures.length; i++) {
  10955. var texture = textures[i];
  10956. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10957. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10958. gl.generateMipmap(gl.TEXTURE_2D);
  10959. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10960. }
  10961. }
  10962. if (onBeforeUnbind) {
  10963. if (textures[0]._MSAAFramebuffer) {
  10964. // Bind the correct framebuffer
  10965. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10966. }
  10967. onBeforeUnbind();
  10968. }
  10969. this.bindUnboundFramebuffer(null);
  10970. };
  10971. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10972. if (texture.generateMipMaps) {
  10973. var gl = this._gl;
  10974. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10975. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10976. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10977. }
  10978. };
  10979. Engine.prototype.flushFramebuffer = function () {
  10980. this._gl.flush();
  10981. };
  10982. Engine.prototype.restoreDefaultFramebuffer = function () {
  10983. if (this._currentRenderTarget) {
  10984. this.unBindFramebuffer(this._currentRenderTarget);
  10985. }
  10986. else {
  10987. this.bindUnboundFramebuffer(null);
  10988. }
  10989. if (this._cachedViewport) {
  10990. this.setViewport(this._cachedViewport);
  10991. }
  10992. this.wipeCaches();
  10993. };
  10994. // UBOs
  10995. Engine.prototype.createUniformBuffer = function (elements) {
  10996. var ubo = this._gl.createBuffer();
  10997. if (!ubo) {
  10998. throw new Error("Unable to create uniform buffer");
  10999. }
  11000. this.bindUniformBuffer(ubo);
  11001. if (elements instanceof Float32Array) {
  11002. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11003. }
  11004. else {
  11005. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11006. }
  11007. this.bindUniformBuffer(null);
  11008. ubo.references = 1;
  11009. return ubo;
  11010. };
  11011. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11012. var ubo = this._gl.createBuffer();
  11013. if (!ubo) {
  11014. throw new Error("Unable to create dynamic uniform buffer");
  11015. }
  11016. this.bindUniformBuffer(ubo);
  11017. if (elements instanceof Float32Array) {
  11018. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11019. }
  11020. else {
  11021. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11022. }
  11023. this.bindUniformBuffer(null);
  11024. ubo.references = 1;
  11025. return ubo;
  11026. };
  11027. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11028. this.bindUniformBuffer(uniformBuffer);
  11029. if (offset === undefined) {
  11030. offset = 0;
  11031. }
  11032. if (count === undefined) {
  11033. if (elements instanceof Float32Array) {
  11034. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11035. }
  11036. else {
  11037. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11038. }
  11039. }
  11040. else {
  11041. if (elements instanceof Float32Array) {
  11042. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11043. }
  11044. else {
  11045. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11046. }
  11047. }
  11048. this.bindUniformBuffer(null);
  11049. };
  11050. // VBOs
  11051. Engine.prototype._resetVertexBufferBinding = function () {
  11052. this.bindArrayBuffer(null);
  11053. this._cachedVertexBuffers = null;
  11054. };
  11055. Engine.prototype.createVertexBuffer = function (vertices) {
  11056. var vbo = this._gl.createBuffer();
  11057. if (!vbo) {
  11058. throw new Error("Unable to create vertex buffer");
  11059. }
  11060. this.bindArrayBuffer(vbo);
  11061. if (vertices instanceof Float32Array) {
  11062. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11063. }
  11064. else {
  11065. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11066. }
  11067. this._resetVertexBufferBinding();
  11068. vbo.references = 1;
  11069. return vbo;
  11070. };
  11071. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11072. var vbo = this._gl.createBuffer();
  11073. if (!vbo) {
  11074. throw new Error("Unable to create dynamic vertex buffer");
  11075. }
  11076. this.bindArrayBuffer(vbo);
  11077. if (vertices instanceof Float32Array) {
  11078. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11079. }
  11080. else {
  11081. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11082. }
  11083. this._resetVertexBufferBinding();
  11084. vbo.references = 1;
  11085. return vbo;
  11086. };
  11087. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11088. if (offset === void 0) { offset = 0; }
  11089. // Force cache update
  11090. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11091. this.bindIndexBuffer(indexBuffer);
  11092. var arrayBuffer;
  11093. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11094. arrayBuffer = indices;
  11095. }
  11096. else {
  11097. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11098. }
  11099. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11100. this._resetIndexBufferBinding();
  11101. };
  11102. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11103. this.bindArrayBuffer(vertexBuffer);
  11104. if (offset === undefined) {
  11105. offset = 0;
  11106. }
  11107. if (count === undefined) {
  11108. if (vertices instanceof Float32Array) {
  11109. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11110. }
  11111. else {
  11112. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11113. }
  11114. }
  11115. else {
  11116. if (vertices instanceof Float32Array) {
  11117. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11118. }
  11119. else {
  11120. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11121. }
  11122. }
  11123. this._resetVertexBufferBinding();
  11124. };
  11125. Engine.prototype._resetIndexBufferBinding = function () {
  11126. this.bindIndexBuffer(null);
  11127. this._cachedIndexBuffer = null;
  11128. };
  11129. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11130. var vbo = this._gl.createBuffer();
  11131. if (!vbo) {
  11132. throw new Error("Unable to create index buffer");
  11133. }
  11134. this.bindIndexBuffer(vbo);
  11135. // Check for 32 bits indices
  11136. var arrayBuffer;
  11137. var need32Bits = false;
  11138. if (indices instanceof Uint16Array) {
  11139. arrayBuffer = indices;
  11140. }
  11141. else {
  11142. //check 32 bit support
  11143. if (this._caps.uintIndices) {
  11144. if (indices instanceof Uint32Array) {
  11145. arrayBuffer = indices;
  11146. need32Bits = true;
  11147. }
  11148. else {
  11149. //number[] or Int32Array, check if 32 bit is necessary
  11150. for (var index = 0; index < indices.length; index++) {
  11151. if (indices[index] > 65535) {
  11152. need32Bits = true;
  11153. break;
  11154. }
  11155. }
  11156. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11157. }
  11158. }
  11159. else {
  11160. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11161. arrayBuffer = new Uint16Array(indices);
  11162. }
  11163. }
  11164. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11165. this._resetIndexBufferBinding();
  11166. vbo.references = 1;
  11167. vbo.is32Bits = need32Bits;
  11168. return vbo;
  11169. };
  11170. Engine.prototype.bindArrayBuffer = function (buffer) {
  11171. if (!this._vaoRecordInProgress) {
  11172. this._unbindVertexArrayObject();
  11173. }
  11174. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11175. };
  11176. Engine.prototype.bindUniformBuffer = function (buffer) {
  11177. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11178. };
  11179. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11180. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11181. };
  11182. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11183. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11184. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11185. };
  11186. ;
  11187. Engine.prototype.bindIndexBuffer = function (buffer) {
  11188. if (!this._vaoRecordInProgress) {
  11189. this._unbindVertexArrayObject();
  11190. }
  11191. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11192. };
  11193. Engine.prototype.bindBuffer = function (buffer, target) {
  11194. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11195. this._gl.bindBuffer(target, buffer);
  11196. this._currentBoundBuffer[target] = buffer;
  11197. }
  11198. };
  11199. Engine.prototype.updateArrayBuffer = function (data) {
  11200. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11201. };
  11202. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11203. var pointer = this._currentBufferPointers[indx];
  11204. var changed = false;
  11205. if (!pointer.active) {
  11206. changed = true;
  11207. pointer.active = true;
  11208. pointer.index = indx;
  11209. pointer.size = size;
  11210. pointer.type = type;
  11211. pointer.normalized = normalized;
  11212. pointer.stride = stride;
  11213. pointer.offset = offset;
  11214. pointer.buffer = buffer;
  11215. }
  11216. else {
  11217. if (pointer.buffer !== buffer) {
  11218. pointer.buffer = buffer;
  11219. changed = true;
  11220. }
  11221. if (pointer.size !== size) {
  11222. pointer.size = size;
  11223. changed = true;
  11224. }
  11225. if (pointer.type !== type) {
  11226. pointer.type = type;
  11227. changed = true;
  11228. }
  11229. if (pointer.normalized !== normalized) {
  11230. pointer.normalized = normalized;
  11231. changed = true;
  11232. }
  11233. if (pointer.stride !== stride) {
  11234. pointer.stride = stride;
  11235. changed = true;
  11236. }
  11237. if (pointer.offset !== offset) {
  11238. pointer.offset = offset;
  11239. changed = true;
  11240. }
  11241. }
  11242. if (changed || this._vaoRecordInProgress) {
  11243. this.bindArrayBuffer(buffer);
  11244. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11245. }
  11246. };
  11247. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11248. if (indexBuffer == null) {
  11249. return;
  11250. }
  11251. if (this._cachedIndexBuffer !== indexBuffer) {
  11252. this._cachedIndexBuffer = indexBuffer;
  11253. this.bindIndexBuffer(indexBuffer);
  11254. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11255. }
  11256. };
  11257. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11258. var attributes = effect.getAttributesNames();
  11259. if (!this._vaoRecordInProgress) {
  11260. this._unbindVertexArrayObject();
  11261. }
  11262. this.unbindAllAttributes();
  11263. for (var index = 0; index < attributes.length; index++) {
  11264. var order = effect.getAttributeLocation(index);
  11265. if (order >= 0) {
  11266. var vertexBuffer = vertexBuffers[attributes[index]];
  11267. if (!vertexBuffer) {
  11268. continue;
  11269. }
  11270. this._gl.enableVertexAttribArray(order);
  11271. if (!this._vaoRecordInProgress) {
  11272. this._vertexAttribArraysEnabled[order] = true;
  11273. }
  11274. var buffer = vertexBuffer.getBuffer();
  11275. if (buffer) {
  11276. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11277. if (vertexBuffer.getIsInstanced()) {
  11278. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11279. if (!this._vaoRecordInProgress) {
  11280. this._currentInstanceLocations.push(order);
  11281. this._currentInstanceBuffers.push(buffer);
  11282. }
  11283. }
  11284. }
  11285. }
  11286. }
  11287. };
  11288. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11289. var vao = this._gl.createVertexArray();
  11290. this._vaoRecordInProgress = true;
  11291. this._gl.bindVertexArray(vao);
  11292. this._mustWipeVertexAttributes = true;
  11293. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11294. this.bindIndexBuffer(indexBuffer);
  11295. this._vaoRecordInProgress = false;
  11296. this._gl.bindVertexArray(null);
  11297. return vao;
  11298. };
  11299. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11300. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11301. this._cachedVertexArrayObject = vertexArrayObject;
  11302. this._gl.bindVertexArray(vertexArrayObject);
  11303. this._cachedVertexBuffers = null;
  11304. this._cachedIndexBuffer = null;
  11305. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11306. this._mustWipeVertexAttributes = true;
  11307. }
  11308. };
  11309. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11310. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11311. this._cachedVertexBuffers = vertexBuffer;
  11312. this._cachedEffectForVertexBuffers = effect;
  11313. var attributesCount = effect.getAttributesCount();
  11314. this._unbindVertexArrayObject();
  11315. this.unbindAllAttributes();
  11316. var offset = 0;
  11317. for (var index = 0; index < attributesCount; index++) {
  11318. if (index < vertexDeclaration.length) {
  11319. var order = effect.getAttributeLocation(index);
  11320. if (order >= 0) {
  11321. this._gl.enableVertexAttribArray(order);
  11322. this._vertexAttribArraysEnabled[order] = true;
  11323. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11324. }
  11325. offset += vertexDeclaration[index] * 4;
  11326. }
  11327. }
  11328. }
  11329. this._bindIndexBufferWithCache(indexBuffer);
  11330. };
  11331. Engine.prototype._unbindVertexArrayObject = function () {
  11332. if (!this._cachedVertexArrayObject) {
  11333. return;
  11334. }
  11335. this._cachedVertexArrayObject = null;
  11336. this._gl.bindVertexArray(null);
  11337. };
  11338. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11339. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11340. this._cachedVertexBuffers = vertexBuffers;
  11341. this._cachedEffectForVertexBuffers = effect;
  11342. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11343. }
  11344. this._bindIndexBufferWithCache(indexBuffer);
  11345. };
  11346. Engine.prototype.unbindInstanceAttributes = function () {
  11347. var boundBuffer;
  11348. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11349. var instancesBuffer = this._currentInstanceBuffers[i];
  11350. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11351. boundBuffer = instancesBuffer;
  11352. this.bindArrayBuffer(instancesBuffer);
  11353. }
  11354. var offsetLocation = this._currentInstanceLocations[i];
  11355. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11356. }
  11357. this._currentInstanceBuffers.length = 0;
  11358. this._currentInstanceLocations.length = 0;
  11359. };
  11360. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11361. this._gl.deleteVertexArray(vao);
  11362. };
  11363. Engine.prototype._releaseBuffer = function (buffer) {
  11364. buffer.references--;
  11365. if (buffer.references === 0) {
  11366. this._gl.deleteBuffer(buffer);
  11367. return true;
  11368. }
  11369. return false;
  11370. };
  11371. Engine.prototype.createInstancesBuffer = function (capacity) {
  11372. var buffer = this._gl.createBuffer();
  11373. if (!buffer) {
  11374. throw new Error("Unable to create instance buffer");
  11375. }
  11376. buffer.capacity = capacity;
  11377. this.bindArrayBuffer(buffer);
  11378. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11379. return buffer;
  11380. };
  11381. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11382. this._gl.deleteBuffer(buffer);
  11383. };
  11384. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11385. this.bindArrayBuffer(instancesBuffer);
  11386. if (data) {
  11387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11388. }
  11389. if (offsetLocations[0].index !== undefined) {
  11390. var stride = 0;
  11391. for (var i = 0; i < offsetLocations.length; i++) {
  11392. var ai = offsetLocations[i];
  11393. stride += ai.attributeSize * 4;
  11394. }
  11395. for (var i = 0; i < offsetLocations.length; i++) {
  11396. var ai = offsetLocations[i];
  11397. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11398. this._gl.enableVertexAttribArray(ai.index);
  11399. this._vertexAttribArraysEnabled[ai.index] = true;
  11400. }
  11401. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11402. this._gl.vertexAttribDivisor(ai.index, 1);
  11403. this._currentInstanceLocations.push(ai.index);
  11404. this._currentInstanceBuffers.push(instancesBuffer);
  11405. }
  11406. }
  11407. else {
  11408. for (var index = 0; index < 4; index++) {
  11409. var offsetLocation = offsetLocations[index];
  11410. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11411. this._gl.enableVertexAttribArray(offsetLocation);
  11412. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11413. }
  11414. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11415. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11416. this._currentInstanceLocations.push(offsetLocation);
  11417. this._currentInstanceBuffers.push(instancesBuffer);
  11418. }
  11419. }
  11420. };
  11421. Engine.prototype.applyStates = function () {
  11422. this._depthCullingState.apply(this._gl);
  11423. this._stencilState.apply(this._gl);
  11424. this._alphaState.apply(this._gl);
  11425. };
  11426. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11427. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11428. };
  11429. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11430. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11431. };
  11432. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11433. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11434. };
  11435. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11436. // Apply states
  11437. this.applyStates();
  11438. this._drawCalls.addCount(1, false);
  11439. // Render
  11440. var drawMode = this.DrawMode(fillMode);
  11441. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11442. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11443. if (instancesCount) {
  11444. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11445. }
  11446. else {
  11447. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11448. }
  11449. };
  11450. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11451. // Apply states
  11452. this.applyStates();
  11453. this._drawCalls.addCount(1, false);
  11454. var drawMode = this.DrawMode(fillMode);
  11455. if (instancesCount) {
  11456. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11457. }
  11458. else {
  11459. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11460. }
  11461. };
  11462. Engine.prototype.DrawMode = function (fillMode) {
  11463. switch (fillMode) {
  11464. // Triangle views
  11465. case BABYLON.Material.TriangleFillMode:
  11466. return this._gl.TRIANGLES;
  11467. case BABYLON.Material.PointFillMode:
  11468. return this._gl.POINTS;
  11469. case BABYLON.Material.WireFrameFillMode:
  11470. return this._gl.LINES;
  11471. // Draw modes
  11472. case BABYLON.Material.PointListDrawMode:
  11473. return this._gl.POINTS;
  11474. case BABYLON.Material.LineListDrawMode:
  11475. return this._gl.LINES;
  11476. case BABYLON.Material.LineLoopDrawMode:
  11477. return this._gl.LINE_LOOP;
  11478. case BABYLON.Material.LineStripDrawMode:
  11479. return this._gl.LINE_STRIP;
  11480. case BABYLON.Material.TriangleStripDrawMode:
  11481. return this._gl.TRIANGLE_STRIP;
  11482. case BABYLON.Material.TriangleFanDrawMode:
  11483. return this._gl.TRIANGLE_FAN;
  11484. default:
  11485. return this._gl.TRIANGLES;
  11486. }
  11487. };
  11488. // Shaders
  11489. Engine.prototype._releaseEffect = function (effect) {
  11490. if (this._compiledEffects[effect._key]) {
  11491. delete this._compiledEffects[effect._key];
  11492. this._deleteProgram(effect.getProgram());
  11493. }
  11494. };
  11495. Engine.prototype._deleteProgram = function (program) {
  11496. if (program) {
  11497. program.__SPECTOR_rebuildProgram = null;
  11498. if (program.transformFeedback) {
  11499. this.deleteTransformFeedback(program.transformFeedback);
  11500. program.transformFeedback = null;
  11501. }
  11502. this._gl.deleteProgram(program);
  11503. }
  11504. };
  11505. /**
  11506. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11507. * @param samplers An array of string used to represent textures
  11508. */
  11509. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11510. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11511. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11512. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11513. if (this._compiledEffects[name]) {
  11514. var compiledEffect = this._compiledEffects[name];
  11515. if (onCompiled && compiledEffect.isReady()) {
  11516. onCompiled(compiledEffect);
  11517. }
  11518. return compiledEffect;
  11519. }
  11520. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11521. effect._key = name;
  11522. this._compiledEffects[name] = effect;
  11523. return effect;
  11524. };
  11525. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11526. if (uniformsNames === void 0) { uniformsNames = []; }
  11527. if (samplers === void 0) { samplers = []; }
  11528. if (defines === void 0) { defines = ""; }
  11529. return this.createEffect({
  11530. vertex: "particles",
  11531. fragmentElement: fragmentName
  11532. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11533. };
  11534. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11535. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11536. context = context || this._gl;
  11537. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11538. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11539. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11540. };
  11541. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11542. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11543. context = context || this._gl;
  11544. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11545. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11546. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11547. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11548. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11549. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11550. return program;
  11551. };
  11552. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11553. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11554. var shaderProgram = context.createProgram();
  11555. if (!shaderProgram) {
  11556. throw new Error("Unable to create program");
  11557. }
  11558. context.attachShader(shaderProgram, vertexShader);
  11559. context.attachShader(shaderProgram, fragmentShader);
  11560. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11561. var transformFeedback = this.createTransformFeedback();
  11562. this.bindTransformFeedback(transformFeedback);
  11563. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11564. shaderProgram.transformFeedback = transformFeedback;
  11565. }
  11566. context.linkProgram(shaderProgram);
  11567. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11568. this.bindTransformFeedback(null);
  11569. }
  11570. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11571. if (!linked) {
  11572. context.validateProgram(shaderProgram);
  11573. var error = context.getProgramInfoLog(shaderProgram);
  11574. if (error) {
  11575. throw new Error(error);
  11576. }
  11577. }
  11578. context.deleteShader(vertexShader);
  11579. context.deleteShader(fragmentShader);
  11580. return shaderProgram;
  11581. };
  11582. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11583. var results = new Array();
  11584. for (var index = 0; index < uniformsNames.length; index++) {
  11585. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11586. }
  11587. return results;
  11588. };
  11589. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11590. var results = [];
  11591. for (var index = 0; index < attributesNames.length; index++) {
  11592. try {
  11593. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11594. }
  11595. catch (e) {
  11596. results.push(-1);
  11597. }
  11598. }
  11599. return results;
  11600. };
  11601. Engine.prototype.enableEffect = function (effect) {
  11602. if (!effect) {
  11603. return;
  11604. }
  11605. // Use program
  11606. this.bindSamplers(effect);
  11607. this._currentEffect = effect;
  11608. if (effect.onBind) {
  11609. effect.onBind(effect);
  11610. }
  11611. effect.onBindObservable.notifyObservers(effect);
  11612. };
  11613. Engine.prototype.setIntArray = function (uniform, array) {
  11614. if (!uniform)
  11615. return;
  11616. this._gl.uniform1iv(uniform, array);
  11617. };
  11618. Engine.prototype.setIntArray2 = function (uniform, array) {
  11619. if (!uniform || array.length % 2 !== 0)
  11620. return;
  11621. this._gl.uniform2iv(uniform, array);
  11622. };
  11623. Engine.prototype.setIntArray3 = function (uniform, array) {
  11624. if (!uniform || array.length % 3 !== 0)
  11625. return;
  11626. this._gl.uniform3iv(uniform, array);
  11627. };
  11628. Engine.prototype.setIntArray4 = function (uniform, array) {
  11629. if (!uniform || array.length % 4 !== 0)
  11630. return;
  11631. this._gl.uniform4iv(uniform, array);
  11632. };
  11633. Engine.prototype.setFloatArray = function (uniform, array) {
  11634. if (!uniform)
  11635. return;
  11636. this._gl.uniform1fv(uniform, array);
  11637. };
  11638. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11639. if (!uniform || array.length % 2 !== 0)
  11640. return;
  11641. this._gl.uniform2fv(uniform, array);
  11642. };
  11643. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11644. if (!uniform || array.length % 3 !== 0)
  11645. return;
  11646. this._gl.uniform3fv(uniform, array);
  11647. };
  11648. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11649. if (!uniform || array.length % 4 !== 0)
  11650. return;
  11651. this._gl.uniform4fv(uniform, array);
  11652. };
  11653. Engine.prototype.setArray = function (uniform, array) {
  11654. if (!uniform)
  11655. return;
  11656. this._gl.uniform1fv(uniform, array);
  11657. };
  11658. Engine.prototype.setArray2 = function (uniform, array) {
  11659. if (!uniform || array.length % 2 !== 0)
  11660. return;
  11661. this._gl.uniform2fv(uniform, array);
  11662. };
  11663. Engine.prototype.setArray3 = function (uniform, array) {
  11664. if (!uniform || array.length % 3 !== 0)
  11665. return;
  11666. this._gl.uniform3fv(uniform, array);
  11667. };
  11668. Engine.prototype.setArray4 = function (uniform, array) {
  11669. if (!uniform || array.length % 4 !== 0)
  11670. return;
  11671. this._gl.uniform4fv(uniform, array);
  11672. };
  11673. Engine.prototype.setMatrices = function (uniform, matrices) {
  11674. if (!uniform)
  11675. return;
  11676. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11677. };
  11678. Engine.prototype.setMatrix = function (uniform, matrix) {
  11679. if (!uniform)
  11680. return;
  11681. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11682. };
  11683. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11684. if (!uniform)
  11685. return;
  11686. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11687. };
  11688. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11689. if (!uniform)
  11690. return;
  11691. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11692. };
  11693. Engine.prototype.setInt = function (uniform, value) {
  11694. if (!uniform)
  11695. return;
  11696. this._gl.uniform1i(uniform, value);
  11697. };
  11698. Engine.prototype.setFloat = function (uniform, value) {
  11699. if (!uniform)
  11700. return;
  11701. this._gl.uniform1f(uniform, value);
  11702. };
  11703. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11704. if (!uniform)
  11705. return;
  11706. this._gl.uniform2f(uniform, x, y);
  11707. };
  11708. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11709. if (!uniform)
  11710. return;
  11711. this._gl.uniform3f(uniform, x, y, z);
  11712. };
  11713. Engine.prototype.setBool = function (uniform, bool) {
  11714. if (!uniform)
  11715. return;
  11716. this._gl.uniform1i(uniform, bool);
  11717. };
  11718. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11719. if (!uniform)
  11720. return;
  11721. this._gl.uniform4f(uniform, x, y, z, w);
  11722. };
  11723. Engine.prototype.setColor3 = function (uniform, color3) {
  11724. if (!uniform)
  11725. return;
  11726. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11727. };
  11728. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11729. if (!uniform)
  11730. return;
  11731. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11732. };
  11733. // States
  11734. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11735. if (zOffset === void 0) { zOffset = 0; }
  11736. if (reverseSide === void 0) { reverseSide = false; }
  11737. // Culling
  11738. if (this._depthCullingState.cull !== culling || force) {
  11739. this._depthCullingState.cull = culling;
  11740. }
  11741. // Cull face
  11742. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11743. if (this._depthCullingState.cullFace !== cullFace || force) {
  11744. this._depthCullingState.cullFace = cullFace;
  11745. }
  11746. // Z offset
  11747. this.setZOffset(zOffset);
  11748. // Front face
  11749. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11750. if (this._depthCullingState.frontFace !== frontFace || force) {
  11751. this._depthCullingState.frontFace = frontFace;
  11752. }
  11753. };
  11754. Engine.prototype.setZOffset = function (value) {
  11755. this._depthCullingState.zOffset = value;
  11756. };
  11757. Engine.prototype.getZOffset = function () {
  11758. return this._depthCullingState.zOffset;
  11759. };
  11760. Engine.prototype.setDepthBuffer = function (enable) {
  11761. this._depthCullingState.depthTest = enable;
  11762. };
  11763. Engine.prototype.getDepthWrite = function () {
  11764. return this._depthCullingState.depthMask;
  11765. };
  11766. Engine.prototype.setDepthWrite = function (enable) {
  11767. this._depthCullingState.depthMask = enable;
  11768. };
  11769. Engine.prototype.setColorWrite = function (enable) {
  11770. this._gl.colorMask(enable, enable, enable, enable);
  11771. this._colorWrite = enable;
  11772. };
  11773. Engine.prototype.getColorWrite = function () {
  11774. return this._colorWrite;
  11775. };
  11776. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11777. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11778. };
  11779. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11780. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11781. if (this._alphaMode === mode) {
  11782. return;
  11783. }
  11784. switch (mode) {
  11785. case Engine.ALPHA_DISABLE:
  11786. this._alphaState.alphaBlend = false;
  11787. break;
  11788. case Engine.ALPHA_PREMULTIPLIED:
  11789. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11790. this._alphaState.alphaBlend = true;
  11791. break;
  11792. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11793. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11794. this._alphaState.alphaBlend = true;
  11795. break;
  11796. case Engine.ALPHA_COMBINE:
  11797. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11798. this._alphaState.alphaBlend = true;
  11799. break;
  11800. case Engine.ALPHA_ONEONE:
  11801. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11802. this._alphaState.alphaBlend = true;
  11803. break;
  11804. case Engine.ALPHA_ADD:
  11805. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11806. this._alphaState.alphaBlend = true;
  11807. break;
  11808. case Engine.ALPHA_SUBTRACT:
  11809. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11810. this._alphaState.alphaBlend = true;
  11811. break;
  11812. case Engine.ALPHA_MULTIPLY:
  11813. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11814. this._alphaState.alphaBlend = true;
  11815. break;
  11816. case Engine.ALPHA_MAXIMIZED:
  11817. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11818. this._alphaState.alphaBlend = true;
  11819. break;
  11820. case Engine.ALPHA_INTERPOLATE:
  11821. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11822. this._alphaState.alphaBlend = true;
  11823. break;
  11824. case Engine.ALPHA_SCREENMODE:
  11825. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11826. this._alphaState.alphaBlend = true;
  11827. break;
  11828. }
  11829. if (!noDepthWriteChange) {
  11830. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11831. }
  11832. this._alphaMode = mode;
  11833. };
  11834. Engine.prototype.getAlphaMode = function () {
  11835. return this._alphaMode;
  11836. };
  11837. // Textures
  11838. Engine.prototype.wipeCaches = function (bruteForce) {
  11839. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11840. return;
  11841. }
  11842. this._currentEffect = null;
  11843. // 6/8/2017: deltakosh: Should not be required anymore.
  11844. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11845. if (bruteForce) {
  11846. this.resetTextureCache();
  11847. this._currentProgram = null;
  11848. this._stencilState.reset();
  11849. this._depthCullingState.reset();
  11850. this.setDepthFunctionToLessOrEqual();
  11851. this._alphaState.reset();
  11852. }
  11853. this._resetVertexBufferBinding();
  11854. this._cachedIndexBuffer = null;
  11855. this._cachedEffectForVertexBuffers = null;
  11856. this._unbindVertexArrayObject();
  11857. this.bindIndexBuffer(null);
  11858. };
  11859. /**
  11860. * Set the compressed texture format to use, based on the formats you have, and the formats
  11861. * supported by the hardware / browser.
  11862. *
  11863. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11864. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11865. * to API arguments needed to compressed textures. This puts the burden on the container
  11866. * generator to house the arcane code for determining these for current & future formats.
  11867. *
  11868. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11869. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11870. *
  11871. * Note: The result of this call is not taken into account when a texture is base64.
  11872. *
  11873. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11874. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11875. *
  11876. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11877. * @returns The extension selected.
  11878. */
  11879. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11880. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11881. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11882. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11883. return this._textureFormatInUse = this._texturesSupported[i];
  11884. }
  11885. }
  11886. }
  11887. // actively set format to nothing, to allow this to be called more than once
  11888. // and possibly fail the 2nd time
  11889. this._textureFormatInUse = null;
  11890. return null;
  11891. };
  11892. Engine.prototype._createTexture = function () {
  11893. var texture = this._gl.createTexture();
  11894. if (!texture) {
  11895. throw new Error("Unable to create texture");
  11896. }
  11897. return texture;
  11898. };
  11899. /**
  11900. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11901. * @param {string} urlArg- This contains one of the following:
  11902. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11903. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11904. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11905. *
  11906. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11907. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11908. * @param {Scene} scene- Needed for loading to the correct scene.
  11909. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11910. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11911. * @param {callback} onError- Optional callback to be called upon failure.
  11912. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11913. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11914. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11915. *
  11916. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11917. */
  11918. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11919. var _this = this;
  11920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11921. if (onLoad === void 0) { onLoad = null; }
  11922. if (onError === void 0) { onError = null; }
  11923. if (buffer === void 0) { buffer = null; }
  11924. if (fallBack === void 0) { fallBack = null; }
  11925. if (format === void 0) { format = null; }
  11926. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11927. var fromData = url.substr(0, 5) === "data:";
  11928. var fromBlob = url.substr(0, 5) === "blob:";
  11929. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11930. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11931. // establish the file extension, if possible
  11932. var lastDot = url.lastIndexOf('.');
  11933. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11934. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  11935. var isTGA = (extension.indexOf(".tga") === 0);
  11936. // determine if a ktx file should be substituted
  11937. var isKTX = false;
  11938. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11939. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11940. isKTX = true;
  11941. }
  11942. if (scene) {
  11943. scene._addPendingData(texture);
  11944. }
  11945. texture.url = url;
  11946. texture.generateMipMaps = !noMipmap;
  11947. texture.samplingMode = samplingMode;
  11948. texture.invertY = invertY;
  11949. if (!this._doNotHandleContextLost) {
  11950. // Keep a link to the buffer only if we plan to handle context lost
  11951. texture._buffer = buffer;
  11952. }
  11953. var onLoadObserver = null;
  11954. if (onLoad && !fallBack) {
  11955. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11956. }
  11957. if (!fallBack)
  11958. this._internalTexturesCache.push(texture);
  11959. var onerror = function (message, exception) {
  11960. if (scene) {
  11961. scene._removePendingData(texture);
  11962. }
  11963. if (onLoadObserver) {
  11964. texture.onLoadedObservable.remove(onLoadObserver);
  11965. }
  11966. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11967. if (isKTX) {
  11968. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11969. }
  11970. else if (BABYLON.Tools.UseFallbackTexture) {
  11971. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11972. }
  11973. if (onError) {
  11974. onError(message || "Unknown error", exception);
  11975. }
  11976. };
  11977. var callback = null;
  11978. // processing for non-image formats
  11979. if (isKTX || isTGA || isDDS) {
  11980. if (isKTX) {
  11981. callback = function (data) {
  11982. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11983. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11984. ktx.uploadLevels(_this._gl, !noMipmap);
  11985. return false;
  11986. }, samplingMode);
  11987. };
  11988. }
  11989. else if (isTGA) {
  11990. callback = function (arrayBuffer) {
  11991. var data = new Uint8Array(arrayBuffer);
  11992. var header = BABYLON.TGATools.GetTGAHeader(data);
  11993. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11994. BABYLON.TGATools.UploadContent(_this._gl, data);
  11995. return false;
  11996. }, samplingMode);
  11997. };
  11998. }
  11999. else if (isDDS) {
  12000. callback = function (data) {
  12001. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12002. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12003. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12004. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12005. return false;
  12006. }, samplingMode);
  12007. };
  12008. }
  12009. if (!buffer) {
  12010. this._loadFile(url, function (data) {
  12011. if (callback) {
  12012. callback(data);
  12013. }
  12014. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12015. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12016. });
  12017. }
  12018. else {
  12019. if (callback) {
  12020. callback(buffer);
  12021. }
  12022. }
  12023. // image format processing
  12024. }
  12025. else {
  12026. var onload = function (img) {
  12027. if (fromBlob && !_this._doNotHandleContextLost) {
  12028. // We need to store the image if we need to rebuild the texture
  12029. // in case of a webgl context lost
  12030. texture._buffer = img;
  12031. }
  12032. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12033. var gl = _this._gl;
  12034. var isPot = (img.width === potWidth && img.height === potHeight);
  12035. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12036. if (isPot) {
  12037. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12038. return false;
  12039. }
  12040. // Using shaders to rescale because canvas.drawImage is lossy
  12041. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12042. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12043. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12044. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12045. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12046. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12047. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12048. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12049. _this._releaseTexture(source);
  12050. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12051. continuationCallback();
  12052. });
  12053. return true;
  12054. }, samplingMode);
  12055. };
  12056. if (!fromData || isBase64)
  12057. if (buffer instanceof HTMLImageElement) {
  12058. onload(buffer);
  12059. }
  12060. else {
  12061. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12062. }
  12063. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12064. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12065. else
  12066. onload(buffer);
  12067. }
  12068. return texture;
  12069. };
  12070. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12071. var _this = this;
  12072. var rtt = this.createRenderTargetTexture({
  12073. width: destination.width,
  12074. height: destination.height,
  12075. }, {
  12076. generateMipMaps: false,
  12077. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12078. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12079. generateDepthBuffer: false,
  12080. generateStencilBuffer: false
  12081. });
  12082. if (!this._rescalePostProcess) {
  12083. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12084. }
  12085. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12086. _this._rescalePostProcess.onApply = function (effect) {
  12087. effect._bindTexture("textureSampler", source);
  12088. };
  12089. var hostingScene = scene;
  12090. if (!hostingScene) {
  12091. hostingScene = _this.scenes[_this.scenes.length - 1];
  12092. }
  12093. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12094. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12095. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12096. _this.unBindFramebuffer(rtt);
  12097. _this._releaseTexture(rtt);
  12098. if (onComplete) {
  12099. onComplete();
  12100. }
  12101. });
  12102. };
  12103. Engine.prototype._getInternalFormat = function (format) {
  12104. var internalFormat = this._gl.RGBA;
  12105. switch (format) {
  12106. case Engine.TEXTUREFORMAT_ALPHA:
  12107. internalFormat = this._gl.ALPHA;
  12108. break;
  12109. case Engine.TEXTUREFORMAT_LUMINANCE:
  12110. internalFormat = this._gl.LUMINANCE;
  12111. break;
  12112. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12113. internalFormat = this._gl.LUMINANCE_ALPHA;
  12114. break;
  12115. case Engine.TEXTUREFORMAT_RGB:
  12116. internalFormat = this._gl.RGB;
  12117. break;
  12118. case Engine.TEXTUREFORMAT_RGBA:
  12119. internalFormat = this._gl.RGBA;
  12120. break;
  12121. }
  12122. return internalFormat;
  12123. };
  12124. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12125. if (compression === void 0) { compression = null; }
  12126. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12127. if (!texture) {
  12128. return;
  12129. }
  12130. var internalFormat = this._getInternalFormat(format);
  12131. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12132. var textureType = this._getWebGLTextureType(type);
  12133. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12134. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12135. if (!this._doNotHandleContextLost) {
  12136. texture._bufferView = data;
  12137. texture.format = format;
  12138. texture.type = type;
  12139. texture.invertY = invertY;
  12140. texture._compression = compression;
  12141. }
  12142. if (texture.width % 4 !== 0) {
  12143. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12144. }
  12145. if (compression && data) {
  12146. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12147. }
  12148. else {
  12149. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12150. }
  12151. if (texture.generateMipMaps) {
  12152. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12153. }
  12154. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12155. // this.resetTextureCache();
  12156. texture.isReady = true;
  12157. };
  12158. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12159. if (compression === void 0) { compression = null; }
  12160. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12161. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12162. texture.baseWidth = width;
  12163. texture.baseHeight = height;
  12164. texture.width = width;
  12165. texture.height = height;
  12166. texture.format = format;
  12167. texture.generateMipMaps = generateMipMaps;
  12168. texture.samplingMode = samplingMode;
  12169. texture.invertY = invertY;
  12170. texture._compression = compression;
  12171. texture.type = type;
  12172. if (!this._doNotHandleContextLost) {
  12173. texture._bufferView = data;
  12174. }
  12175. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12176. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12177. // Filters
  12178. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12179. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12180. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12181. if (generateMipMaps) {
  12182. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12183. }
  12184. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12185. this._internalTexturesCache.push(texture);
  12186. return texture;
  12187. };
  12188. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12189. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12190. texture.baseWidth = width;
  12191. texture.baseHeight = height;
  12192. if (generateMipMaps) {
  12193. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12194. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12195. }
  12196. // this.resetTextureCache();
  12197. texture.width = width;
  12198. texture.height = height;
  12199. texture.isReady = false;
  12200. texture.generateMipMaps = generateMipMaps;
  12201. texture.samplingMode = samplingMode;
  12202. this.updateTextureSamplingMode(samplingMode, texture);
  12203. this._internalTexturesCache.push(texture);
  12204. return texture;
  12205. };
  12206. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12207. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12208. if (texture.isCube) {
  12209. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12210. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12211. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12212. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12213. }
  12214. else if (texture.is3D) {
  12215. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12216. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12217. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12218. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12219. }
  12220. else {
  12221. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12222. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12223. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12224. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12225. }
  12226. texture.samplingMode = samplingMode;
  12227. };
  12228. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12229. if (premulAlpha === void 0) { premulAlpha = false; }
  12230. if (!texture) {
  12231. return;
  12232. }
  12233. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12234. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12235. if (premulAlpha) {
  12236. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12237. }
  12238. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12239. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12240. if (texture.generateMipMaps) {
  12241. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12242. }
  12243. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12244. if (premulAlpha) {
  12245. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12246. }
  12247. texture.isReady = true;
  12248. };
  12249. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12250. if (!texture || texture._isDisabled) {
  12251. return;
  12252. }
  12253. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12254. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12255. try {
  12256. // Testing video texture support
  12257. if (this._videoTextureSupported === undefined) {
  12258. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12259. if (this._gl.getError() !== 0) {
  12260. this._videoTextureSupported = false;
  12261. }
  12262. else {
  12263. this._videoTextureSupported = true;
  12264. }
  12265. }
  12266. // Copy video through the current working canvas if video texture is not supported
  12267. if (!this._videoTextureSupported) {
  12268. if (!texture._workingCanvas) {
  12269. texture._workingCanvas = document.createElement("canvas");
  12270. var context = texture._workingCanvas.getContext("2d");
  12271. if (!context) {
  12272. throw new Error("Unable to get 2d context");
  12273. }
  12274. texture._workingContext = context;
  12275. texture._workingCanvas.width = texture.width;
  12276. texture._workingCanvas.height = texture.height;
  12277. }
  12278. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12279. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12280. }
  12281. else {
  12282. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12283. }
  12284. if (texture.generateMipMaps) {
  12285. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12286. }
  12287. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12288. // this.resetTextureCache();
  12289. texture.isReady = true;
  12290. }
  12291. catch (ex) {
  12292. // Something unexpected
  12293. // Let's disable the texture
  12294. texture._isDisabled = true;
  12295. }
  12296. };
  12297. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12298. var fullOptions = new RenderTargetCreationOptions();
  12299. if (options !== undefined && typeof options === "object") {
  12300. fullOptions.generateMipMaps = options.generateMipMaps;
  12301. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12302. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12303. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12304. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12305. }
  12306. else {
  12307. fullOptions.generateMipMaps = options;
  12308. fullOptions.generateDepthBuffer = true;
  12309. fullOptions.generateStencilBuffer = false;
  12310. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12311. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12312. }
  12313. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12314. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12315. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12316. }
  12317. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12318. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12319. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12320. }
  12321. var gl = this._gl;
  12322. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12323. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12324. var width = size.width || size;
  12325. var height = size.height || size;
  12326. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12327. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12328. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12329. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12330. }
  12331. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12332. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12333. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12334. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12335. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12336. // Create the framebuffer
  12337. var framebuffer = gl.createFramebuffer();
  12338. this.bindUnboundFramebuffer(framebuffer);
  12339. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12340. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12341. if (fullOptions.generateMipMaps) {
  12342. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12343. }
  12344. // Unbind
  12345. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12346. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12347. this.bindUnboundFramebuffer(null);
  12348. texture._framebuffer = framebuffer;
  12349. texture.baseWidth = width;
  12350. texture.baseHeight = height;
  12351. texture.width = width;
  12352. texture.height = height;
  12353. texture.isReady = true;
  12354. texture.samples = 1;
  12355. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12356. texture.samplingMode = fullOptions.samplingMode;
  12357. texture.type = fullOptions.type;
  12358. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12359. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12360. // this.resetTextureCache();
  12361. this._internalTexturesCache.push(texture);
  12362. return texture;
  12363. };
  12364. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12365. var generateMipMaps = false;
  12366. var generateDepthBuffer = true;
  12367. var generateStencilBuffer = false;
  12368. var generateDepthTexture = false;
  12369. var textureCount = 1;
  12370. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12371. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12372. var types = [], samplingModes = [];
  12373. if (options !== undefined) {
  12374. generateMipMaps = options.generateMipMaps;
  12375. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12376. generateStencilBuffer = options.generateStencilBuffer;
  12377. generateDepthTexture = options.generateDepthTexture;
  12378. textureCount = options.textureCount || 1;
  12379. if (options.types) {
  12380. types = options.types;
  12381. }
  12382. if (options.samplingModes) {
  12383. samplingModes = options.samplingModes;
  12384. }
  12385. }
  12386. var gl = this._gl;
  12387. // Create the framebuffer
  12388. var framebuffer = gl.createFramebuffer();
  12389. this.bindUnboundFramebuffer(framebuffer);
  12390. var width = size.width || size;
  12391. var height = size.height || size;
  12392. var textures = [];
  12393. var attachments = [];
  12394. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12395. for (var i = 0; i < textureCount; i++) {
  12396. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12397. var type = types[i] || defaultType;
  12398. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12399. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12400. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12401. }
  12402. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12403. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12404. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12405. }
  12406. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12407. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12408. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12409. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12410. }
  12411. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12412. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12413. textures.push(texture);
  12414. attachments.push(attachment);
  12415. gl.activeTexture(gl["TEXTURE" + i]);
  12416. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12418. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12419. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12420. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12421. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12422. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12423. if (generateMipMaps) {
  12424. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12425. }
  12426. // Unbind
  12427. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12428. texture._framebuffer = framebuffer;
  12429. texture._depthStencilBuffer = depthStencilBuffer;
  12430. texture.baseWidth = width;
  12431. texture.baseHeight = height;
  12432. texture.width = width;
  12433. texture.height = height;
  12434. texture.isReady = true;
  12435. texture.samples = 1;
  12436. texture.generateMipMaps = generateMipMaps;
  12437. texture.samplingMode = samplingMode;
  12438. texture.type = type;
  12439. texture._generateDepthBuffer = generateDepthBuffer;
  12440. texture._generateStencilBuffer = generateStencilBuffer;
  12441. texture._attachments = attachments;
  12442. this._internalTexturesCache.push(texture);
  12443. }
  12444. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12445. // Depth texture
  12446. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12447. gl.activeTexture(gl.TEXTURE0);
  12448. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12450. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12453. 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);
  12454. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12455. depthTexture._framebuffer = framebuffer;
  12456. depthTexture.baseWidth = width;
  12457. depthTexture.baseHeight = height;
  12458. depthTexture.width = width;
  12459. depthTexture.height = height;
  12460. depthTexture.isReady = true;
  12461. depthTexture.samples = 1;
  12462. depthTexture.generateMipMaps = generateMipMaps;
  12463. depthTexture.samplingMode = gl.NEAREST;
  12464. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12465. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12466. textures.push(depthTexture);
  12467. this._internalTexturesCache.push(depthTexture);
  12468. }
  12469. gl.drawBuffers(attachments);
  12470. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12471. this.bindUnboundFramebuffer(null);
  12472. this.resetTextureCache();
  12473. return textures;
  12474. };
  12475. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12476. if (samples === void 0) { samples = 1; }
  12477. var depthStencilBuffer = null;
  12478. var gl = this._gl;
  12479. // Create the depth/stencil buffer
  12480. if (generateStencilBuffer) {
  12481. depthStencilBuffer = gl.createRenderbuffer();
  12482. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12483. if (samples > 1) {
  12484. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12485. }
  12486. else {
  12487. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12488. }
  12489. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12490. }
  12491. else if (generateDepthBuffer) {
  12492. depthStencilBuffer = gl.createRenderbuffer();
  12493. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12494. if (samples > 1) {
  12495. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12496. }
  12497. else {
  12498. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12499. }
  12500. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12501. }
  12502. return depthStencilBuffer;
  12503. };
  12504. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12505. if (this.webGLVersion < 2 || !texture) {
  12506. return 1;
  12507. }
  12508. if (texture.samples === samples) {
  12509. return samples;
  12510. }
  12511. var gl = this._gl;
  12512. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12513. // Dispose previous render buffers
  12514. if (texture._depthStencilBuffer) {
  12515. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12516. texture._depthStencilBuffer = null;
  12517. }
  12518. if (texture._MSAAFramebuffer) {
  12519. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12520. texture._MSAAFramebuffer = null;
  12521. }
  12522. if (texture._MSAARenderBuffer) {
  12523. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12524. texture._MSAARenderBuffer = null;
  12525. }
  12526. if (samples > 1) {
  12527. var framebuffer = gl.createFramebuffer();
  12528. if (!framebuffer) {
  12529. throw new Error("Unable to create multi sampled framebuffer");
  12530. }
  12531. texture._MSAAFramebuffer = framebuffer;
  12532. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12533. var colorRenderbuffer = gl.createRenderbuffer();
  12534. if (!colorRenderbuffer) {
  12535. throw new Error("Unable to create multi sampled framebuffer");
  12536. }
  12537. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12538. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12539. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12540. texture._MSAARenderBuffer = colorRenderbuffer;
  12541. }
  12542. else {
  12543. this.bindUnboundFramebuffer(texture._framebuffer);
  12544. }
  12545. texture.samples = samples;
  12546. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12547. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12548. this.bindUnboundFramebuffer(null);
  12549. return samples;
  12550. };
  12551. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12552. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12553. return 1;
  12554. }
  12555. if (textures[0].samples === samples) {
  12556. return samples;
  12557. }
  12558. var gl = this._gl;
  12559. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12560. // Dispose previous render buffers
  12561. if (textures[0]._depthStencilBuffer) {
  12562. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12563. textures[0]._depthStencilBuffer = null;
  12564. }
  12565. if (textures[0]._MSAAFramebuffer) {
  12566. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12567. textures[0]._MSAAFramebuffer = null;
  12568. }
  12569. for (var i = 0; i < textures.length; i++) {
  12570. if (textures[i]._MSAARenderBuffer) {
  12571. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12572. textures[i]._MSAARenderBuffer = null;
  12573. }
  12574. }
  12575. if (samples > 1) {
  12576. var framebuffer = gl.createFramebuffer();
  12577. if (!framebuffer) {
  12578. throw new Error("Unable to create multi sampled framebuffer");
  12579. }
  12580. this.bindUnboundFramebuffer(framebuffer);
  12581. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12582. var attachments = [];
  12583. for (var i = 0; i < textures.length; i++) {
  12584. var texture = textures[i];
  12585. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12586. var colorRenderbuffer = gl.createRenderbuffer();
  12587. if (!colorRenderbuffer) {
  12588. throw new Error("Unable to create multi sampled framebuffer");
  12589. }
  12590. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12591. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12592. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12593. texture._MSAAFramebuffer = framebuffer;
  12594. texture._MSAARenderBuffer = colorRenderbuffer;
  12595. texture.samples = samples;
  12596. texture._depthStencilBuffer = depthStencilBuffer;
  12597. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12598. attachments.push(attachment);
  12599. }
  12600. gl.drawBuffers(attachments);
  12601. }
  12602. else {
  12603. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12604. }
  12605. this.bindUnboundFramebuffer(null);
  12606. return samples;
  12607. };
  12608. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12609. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12610. };
  12611. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12612. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12613. };
  12614. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12615. var gl = this._gl;
  12616. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12617. var generateMipMaps = true;
  12618. var generateDepthBuffer = true;
  12619. var generateStencilBuffer = false;
  12620. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12621. if (options !== undefined) {
  12622. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12623. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12624. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12625. if (options.samplingMode !== undefined) {
  12626. samplingMode = options.samplingMode;
  12627. }
  12628. }
  12629. texture.isCube = true;
  12630. texture.generateMipMaps = generateMipMaps;
  12631. texture.samples = 1;
  12632. texture.samplingMode = samplingMode;
  12633. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12634. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12635. for (var face = 0; face < 6; face++) {
  12636. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12637. }
  12638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12640. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12641. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12642. // Create the framebuffer
  12643. var framebuffer = gl.createFramebuffer();
  12644. this.bindUnboundFramebuffer(framebuffer);
  12645. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12646. // Mipmaps
  12647. if (texture.generateMipMaps) {
  12648. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12649. }
  12650. // Unbind
  12651. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12652. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12653. this.bindUnboundFramebuffer(null);
  12654. texture._framebuffer = framebuffer;
  12655. texture.width = size;
  12656. texture.height = size;
  12657. texture.isReady = true;
  12658. //this.resetTextureCache();
  12659. this._internalTexturesCache.push(texture);
  12660. return texture;
  12661. };
  12662. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12663. var _this = this;
  12664. if (onLoad === void 0) { onLoad = null; }
  12665. if (onError === void 0) { onError = null; }
  12666. if (forcedExtension === void 0) { forcedExtension = null; }
  12667. var callback = function (loadData) {
  12668. if (!loadData) {
  12669. if (onLoad) {
  12670. onLoad(null);
  12671. }
  12672. return;
  12673. }
  12674. var texture = loadData.texture;
  12675. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12676. texture._lodGenerationScale = scale;
  12677. texture._lodGenerationOffset = offset;
  12678. if (_this._caps.textureLOD) {
  12679. // Do not add extra process if texture lod is supported.
  12680. if (onLoad) {
  12681. onLoad(texture);
  12682. }
  12683. return;
  12684. }
  12685. var mipSlices = 3;
  12686. var gl = _this._gl;
  12687. var width = loadData.width;
  12688. if (!width) {
  12689. return;
  12690. }
  12691. var textures = [];
  12692. for (var i = 0; i < mipSlices; i++) {
  12693. //compute LOD from even spacing in smoothness (matching shader calculation)
  12694. var smoothness = i / (mipSlices - 1);
  12695. var roughness = 1 - smoothness;
  12696. var minLODIndex = offset; // roughness = 0
  12697. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12698. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12699. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12700. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12701. glTextureFromLod.isCube = true;
  12702. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12707. if (loadData.isDDS) {
  12708. var info = loadData.info;
  12709. var data = loadData.data;
  12710. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12711. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12712. }
  12713. else {
  12714. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12715. }
  12716. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12717. // Wrap in a base texture for easy binding.
  12718. var lodTexture = new BABYLON.BaseTexture(scene);
  12719. lodTexture.isCube = true;
  12720. lodTexture._texture = glTextureFromLod;
  12721. glTextureFromLod.isReady = true;
  12722. textures.push(lodTexture);
  12723. }
  12724. texture._lodTextureHigh = textures[2];
  12725. texture._lodTextureMid = textures[1];
  12726. texture._lodTextureLow = textures[0];
  12727. if (onLoad) {
  12728. onLoad(texture);
  12729. }
  12730. };
  12731. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12732. };
  12733. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12734. var _this = this;
  12735. if (onLoad === void 0) { onLoad = null; }
  12736. if (onError === void 0) { onError = null; }
  12737. if (forcedExtension === void 0) { forcedExtension = null; }
  12738. var gl = this._gl;
  12739. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12740. texture.isCube = true;
  12741. texture.url = rootUrl;
  12742. texture.generateMipMaps = !noMipmap;
  12743. if (!this._doNotHandleContextLost) {
  12744. texture._extension = forcedExtension;
  12745. texture._files = files;
  12746. }
  12747. var isKTX = false;
  12748. var isDDS = false;
  12749. var lastDot = rootUrl.lastIndexOf('.');
  12750. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12751. if (this._textureFormatInUse) {
  12752. extension = this._textureFormatInUse;
  12753. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12754. isKTX = true;
  12755. }
  12756. else {
  12757. isDDS = (extension === ".dds");
  12758. }
  12759. var onerror = function (request, exception) {
  12760. if (onError && request) {
  12761. onError(request.status + " " + request.statusText, exception);
  12762. }
  12763. };
  12764. if (isKTX) {
  12765. this._loadFile(rootUrl, function (data) {
  12766. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12767. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12768. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12769. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12770. ktx.uploadLevels(_this._gl, !noMipmap);
  12771. _this.setCubeMapTextureParams(gl, loadMipmap);
  12772. texture.width = ktx.pixelWidth;
  12773. texture.height = ktx.pixelHeight;
  12774. texture.isReady = true;
  12775. }, undefined, undefined, true, onerror);
  12776. }
  12777. else if (isDDS) {
  12778. if (files && files.length === 6) {
  12779. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12780. var info;
  12781. var loadMipmap = false;
  12782. var width = 0;
  12783. for (var index = 0; index < imgs.length; index++) {
  12784. var data = imgs[index];
  12785. info = BABYLON.DDSTools.GetDDSInfo(data);
  12786. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12787. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12788. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12789. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12790. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12791. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12792. }
  12793. texture.width = info.width;
  12794. texture.height = info.height;
  12795. texture.type = info.textureType;
  12796. width = info.width;
  12797. }
  12798. _this.setCubeMapTextureParams(gl, loadMipmap);
  12799. texture.isReady = true;
  12800. if (onLoad) {
  12801. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12802. }
  12803. }, files, onError);
  12804. }
  12805. else {
  12806. this._loadFile(rootUrl, function (data) {
  12807. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12808. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12809. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12810. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12811. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12812. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12813. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12814. }
  12815. _this.setCubeMapTextureParams(gl, loadMipmap);
  12816. texture.width = info.width;
  12817. texture.height = info.height;
  12818. texture.isReady = true;
  12819. texture.type = info.textureType;
  12820. if (onLoad) {
  12821. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12822. }
  12823. }, undefined, undefined, true, onerror);
  12824. }
  12825. }
  12826. else {
  12827. if (!files) {
  12828. throw new Error("Cannot load cubemap because files were not defined");
  12829. }
  12830. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12831. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12832. var height = width;
  12833. _this._prepareWorkingCanvas();
  12834. if (!_this._workingCanvas || !_this._workingContext) {
  12835. return;
  12836. }
  12837. _this._workingCanvas.width = width;
  12838. _this._workingCanvas.height = height;
  12839. var faces = [
  12840. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12841. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12842. ];
  12843. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12844. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12845. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12846. for (var index = 0; index < faces.length; index++) {
  12847. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12848. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12849. }
  12850. if (!noMipmap) {
  12851. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12852. }
  12853. _this.setCubeMapTextureParams(gl, !noMipmap);
  12854. texture.width = width;
  12855. texture.height = height;
  12856. texture.isReady = true;
  12857. if (format) {
  12858. texture.format = format;
  12859. }
  12860. texture.onLoadedObservable.notifyObservers(texture);
  12861. texture.onLoadedObservable.clear();
  12862. if (onLoad) {
  12863. onLoad();
  12864. }
  12865. }, files, onError);
  12866. }
  12867. this._internalTexturesCache.push(texture);
  12868. return texture;
  12869. };
  12870. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12875. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12876. // this.resetTextureCache();
  12877. };
  12878. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12879. if (compression === void 0) { compression = null; }
  12880. if (level === void 0) { level = 0; }
  12881. texture._bufferViewArray = data;
  12882. texture.format = format;
  12883. texture.type = type;
  12884. texture.invertY = invertY;
  12885. texture._compression = compression;
  12886. var gl = this._gl;
  12887. var textureType = this._getWebGLTextureType(type);
  12888. var internalFormat = this._getInternalFormat(format);
  12889. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12890. var needConversion = false;
  12891. if (internalFormat === gl.RGB) {
  12892. internalFormat = gl.RGBA;
  12893. needConversion = true;
  12894. }
  12895. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12896. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12897. if (texture.width % 4 !== 0) {
  12898. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12899. }
  12900. // Data are known to be in +X +Y +Z -X -Y -Z
  12901. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12902. var faceData = data[faceIndex];
  12903. if (compression) {
  12904. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12905. }
  12906. else {
  12907. if (needConversion) {
  12908. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12909. }
  12910. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12911. }
  12912. }
  12913. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12914. if (isPot && texture.generateMipMaps && level === 0) {
  12915. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12916. }
  12917. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12918. // this.resetTextureCache();
  12919. texture.isReady = true;
  12920. };
  12921. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12922. if (compression === void 0) { compression = null; }
  12923. var gl = this._gl;
  12924. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12925. texture.isCube = true;
  12926. texture.generateMipMaps = generateMipMaps;
  12927. texture.format = format;
  12928. texture.type = type;
  12929. if (!this._doNotHandleContextLost) {
  12930. texture._bufferViewArray = data;
  12931. }
  12932. var textureType = this._getWebGLTextureType(type);
  12933. var internalFormat = this._getInternalFormat(format);
  12934. if (internalFormat === gl.RGB) {
  12935. internalFormat = gl.RGBA;
  12936. }
  12937. var width = size;
  12938. var height = width;
  12939. texture.width = width;
  12940. texture.height = height;
  12941. // Double check on POT to generate Mips.
  12942. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12943. if (!isPot) {
  12944. generateMipMaps = false;
  12945. }
  12946. // Upload data if needed. The texture won't be ready until then.
  12947. if (data) {
  12948. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12949. }
  12950. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12951. // Filters
  12952. if (data && generateMipMaps) {
  12953. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12954. }
  12955. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12957. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12958. }
  12959. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12962. }
  12963. else {
  12964. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12967. }
  12968. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12969. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12970. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12971. return texture;
  12972. };
  12973. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12974. var _this = this;
  12975. if (onLoad === void 0) { onLoad = null; }
  12976. if (onError === void 0) { onError = null; }
  12977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12978. if (invertY === void 0) { invertY = false; }
  12979. var gl = this._gl;
  12980. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12981. scene._addPendingData(texture);
  12982. texture.url = url;
  12983. this._internalTexturesCache.push(texture);
  12984. var onerror = function (request, exception) {
  12985. scene._removePendingData(texture);
  12986. if (onError && request) {
  12987. onError(request.status + " " + request.statusText, exception);
  12988. }
  12989. };
  12990. var internalCallback = function (data) {
  12991. var width = texture.width;
  12992. var faceDataArrays = callback(data);
  12993. if (!faceDataArrays) {
  12994. return;
  12995. }
  12996. if (mipmmapGenerator) {
  12997. var textureType = _this._getWebGLTextureType(type);
  12998. var internalFormat = _this._getInternalFormat(format);
  12999. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13000. var needConversion = false;
  13001. if (internalFormat === gl.RGB) {
  13002. internalFormat = gl.RGBA;
  13003. needConversion = true;
  13004. }
  13005. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13006. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13007. var mipData = mipmmapGenerator(faceDataArrays);
  13008. for (var level = 0; level < mipData.length; level++) {
  13009. var mipSize = width >> level;
  13010. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13011. var mipFaceData = mipData[level][faceIndex];
  13012. if (needConversion) {
  13013. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13014. }
  13015. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13016. }
  13017. }
  13018. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13019. }
  13020. else {
  13021. texture.generateMipMaps = !noMipmap;
  13022. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13023. }
  13024. texture.isReady = true;
  13025. // this.resetTextureCache();
  13026. scene._removePendingData(texture);
  13027. if (onLoad) {
  13028. onLoad();
  13029. }
  13030. };
  13031. this._loadFile(url, function (data) {
  13032. internalCallback(data);
  13033. }, undefined, scene.database, true, onerror);
  13034. return texture;
  13035. };
  13036. ;
  13037. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13038. if (compression === void 0) { compression = null; }
  13039. var internalFormat = this._getInternalFormat(format);
  13040. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13041. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13042. if (!this._doNotHandleContextLost) {
  13043. texture._bufferView = data;
  13044. texture.format = format;
  13045. texture.invertY = invertY;
  13046. texture._compression = compression;
  13047. }
  13048. if (texture.width % 4 !== 0) {
  13049. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13050. }
  13051. if (compression && data) {
  13052. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13053. }
  13054. else {
  13055. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13056. }
  13057. if (texture.generateMipMaps) {
  13058. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13059. }
  13060. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13061. // this.resetTextureCache();
  13062. texture.isReady = true;
  13063. };
  13064. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13065. if (compression === void 0) { compression = null; }
  13066. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13067. texture.baseWidth = width;
  13068. texture.baseHeight = height;
  13069. texture.baseDepth = depth;
  13070. texture.width = width;
  13071. texture.height = height;
  13072. texture.depth = depth;
  13073. texture.format = format;
  13074. texture.generateMipMaps = generateMipMaps;
  13075. texture.samplingMode = samplingMode;
  13076. texture.is3D = true;
  13077. if (!this._doNotHandleContextLost) {
  13078. texture._bufferView = data;
  13079. }
  13080. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13081. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13082. // Filters
  13083. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13084. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13085. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13086. if (generateMipMaps) {
  13087. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13088. }
  13089. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13090. this._internalTexturesCache.push(texture);
  13091. return texture;
  13092. };
  13093. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13094. var gl = this._gl;
  13095. if (!gl) {
  13096. return;
  13097. }
  13098. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13100. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13101. if (!noMipmap && !isCompressed) {
  13102. gl.generateMipmap(gl.TEXTURE_2D);
  13103. }
  13104. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13105. // this.resetTextureCache();
  13106. if (scene) {
  13107. scene._removePendingData(texture);
  13108. }
  13109. texture.onLoadedObservable.notifyObservers(texture);
  13110. texture.onLoadedObservable.clear();
  13111. };
  13112. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13113. var _this = this;
  13114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13115. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13116. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13117. var gl = this._gl;
  13118. if (!gl) {
  13119. return;
  13120. }
  13121. if (!texture._webGLTexture) {
  13122. // this.resetTextureCache();
  13123. if (scene) {
  13124. scene._removePendingData(texture);
  13125. }
  13126. return;
  13127. }
  13128. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13129. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13130. texture.baseWidth = width;
  13131. texture.baseHeight = height;
  13132. texture.width = potWidth;
  13133. texture.height = potHeight;
  13134. texture.isReady = true;
  13135. if (processFunction(potWidth, potHeight, function () {
  13136. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13137. })) {
  13138. // Returning as texture needs extra async steps
  13139. return;
  13140. }
  13141. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13142. };
  13143. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13144. // Create new RGBA data container.
  13145. var rgbaData;
  13146. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13147. rgbaData = new Float32Array(width * height * 4);
  13148. }
  13149. else {
  13150. rgbaData = new Uint32Array(width * height * 4);
  13151. }
  13152. // Convert each pixel.
  13153. for (var x = 0; x < width; x++) {
  13154. for (var y = 0; y < height; y++) {
  13155. var index = (y * width + x) * 3;
  13156. var newIndex = (y * width + x) * 4;
  13157. // Map Old Value to new value.
  13158. rgbaData[newIndex + 0] = rgbData[index + 0];
  13159. rgbaData[newIndex + 1] = rgbData[index + 1];
  13160. rgbaData[newIndex + 2] = rgbData[index + 2];
  13161. // Add fully opaque alpha channel.
  13162. rgbaData[newIndex + 3] = 1;
  13163. }
  13164. }
  13165. return rgbaData;
  13166. };
  13167. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13168. var gl = this._gl;
  13169. if (texture._framebuffer) {
  13170. gl.deleteFramebuffer(texture._framebuffer);
  13171. texture._framebuffer = null;
  13172. }
  13173. if (texture._depthStencilBuffer) {
  13174. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13175. texture._depthStencilBuffer = null;
  13176. }
  13177. if (texture._MSAAFramebuffer) {
  13178. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13179. texture._MSAAFramebuffer = null;
  13180. }
  13181. if (texture._MSAARenderBuffer) {
  13182. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13183. texture._MSAARenderBuffer = null;
  13184. }
  13185. };
  13186. Engine.prototype._releaseTexture = function (texture) {
  13187. var gl = this._gl;
  13188. this._releaseFramebufferObjects(texture);
  13189. gl.deleteTexture(texture._webGLTexture);
  13190. // Unbind channels
  13191. this.unbindAllTextures();
  13192. var index = this._internalTexturesCache.indexOf(texture);
  13193. if (index !== -1) {
  13194. this._internalTexturesCache.splice(index, 1);
  13195. }
  13196. // Integrated fixed lod samplers.
  13197. if (texture._lodTextureHigh) {
  13198. texture._lodTextureHigh.dispose();
  13199. }
  13200. if (texture._lodTextureMid) {
  13201. texture._lodTextureMid.dispose();
  13202. }
  13203. if (texture._lodTextureLow) {
  13204. texture._lodTextureLow.dispose();
  13205. }
  13206. };
  13207. Engine.prototype.setProgram = function (program) {
  13208. if (this._currentProgram !== program) {
  13209. this._gl.useProgram(program);
  13210. this._currentProgram = program;
  13211. }
  13212. };
  13213. Engine.prototype.bindSamplers = function (effect) {
  13214. this.setProgram(effect.getProgram());
  13215. var samplers = effect.getSamplers();
  13216. for (var index = 0; index < samplers.length; index++) {
  13217. var uniform = effect.getUniform(samplers[index]);
  13218. if (uniform) {
  13219. this._boundUniforms[index] = uniform;
  13220. }
  13221. }
  13222. this._currentEffect = null;
  13223. };
  13224. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13225. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13226. return;
  13227. }
  13228. // Remove
  13229. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13230. // Bind last to it
  13231. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13232. // Bind to dummy
  13233. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13234. };
  13235. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13236. if (!internalTexture) {
  13237. return -1;
  13238. }
  13239. internalTexture._initialSlot = channel;
  13240. if (this.disableTextureBindingOptimization) {
  13241. if (channel !== internalTexture._designatedSlot) {
  13242. this._textureCollisions.addCount(1, false);
  13243. }
  13244. }
  13245. else {
  13246. if (channel !== internalTexture._designatedSlot) {
  13247. if (internalTexture._designatedSlot > -1) {
  13248. return internalTexture._designatedSlot;
  13249. }
  13250. else {
  13251. // No slot for this texture, let's pick a new one (if we find a free slot)
  13252. if (this._nextFreeTextureSlots.length) {
  13253. return this._nextFreeTextureSlots[0];
  13254. }
  13255. // We need to recycle the oldest bound texture, sorry.
  13256. this._textureCollisions.addCount(1, false);
  13257. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13258. }
  13259. }
  13260. }
  13261. return channel;
  13262. };
  13263. Engine.prototype._linkTrackers = function (previous, next) {
  13264. previous.next = next;
  13265. next.previous = previous;
  13266. };
  13267. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13268. var currentSlot = internalTexture._designatedSlot;
  13269. if (currentSlot === -1) {
  13270. return -1;
  13271. }
  13272. internalTexture._designatedSlot = -1;
  13273. if (this.disableTextureBindingOptimization) {
  13274. return -1;
  13275. }
  13276. // Remove from bound list
  13277. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13278. // Free the slot
  13279. this._boundTexturesCache[currentSlot] = null;
  13280. this._nextFreeTextureSlots.push(currentSlot);
  13281. return currentSlot;
  13282. };
  13283. Engine.prototype._activateCurrentTexture = function () {
  13284. if (this._currentTextureChannel !== this._activeChannel) {
  13285. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13286. this._currentTextureChannel = this._activeChannel;
  13287. }
  13288. };
  13289. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13290. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13291. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13292. this._activeChannel = texture._designatedSlot;
  13293. }
  13294. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13295. var isTextureForRendering = texture && texture._initialSlot > -1;
  13296. if (currentTextureBound !== texture) {
  13297. if (currentTextureBound) {
  13298. this._removeDesignatedSlot(currentTextureBound);
  13299. }
  13300. this._activateCurrentTexture();
  13301. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13302. this._boundTexturesCache[this._activeChannel] = texture;
  13303. if (texture) {
  13304. if (!this.disableTextureBindingOptimization) {
  13305. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13306. if (slotIndex > -1) {
  13307. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13308. }
  13309. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13310. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13311. }
  13312. texture._designatedSlot = this._activeChannel;
  13313. }
  13314. }
  13315. else if (forTextureDataUpdate) {
  13316. this._activateCurrentTexture();
  13317. }
  13318. if (isTextureForRendering && !forTextureDataUpdate) {
  13319. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13320. }
  13321. };
  13322. Engine.prototype._bindTexture = function (channel, texture) {
  13323. if (channel < 0) {
  13324. return;
  13325. }
  13326. if (texture) {
  13327. channel = this._getCorrectTextureChannel(channel, texture);
  13328. }
  13329. this._activeChannel = channel;
  13330. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13331. };
  13332. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13333. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13334. };
  13335. Engine.prototype.unbindAllTextures = function () {
  13336. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13337. this._activeChannel = channel;
  13338. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13339. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13340. if (this.webGLVersion > 1) {
  13341. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13342. }
  13343. }
  13344. };
  13345. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13346. if (channel < 0) {
  13347. return;
  13348. }
  13349. if (uniform) {
  13350. this._boundUniforms[channel] = uniform;
  13351. }
  13352. this._setTexture(channel, texture);
  13353. };
  13354. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13355. var uniform = this._boundUniforms[sourceSlot];
  13356. if (uniform._currentState === destination) {
  13357. return;
  13358. }
  13359. this._gl.uniform1i(uniform, destination);
  13360. uniform._currentState = destination;
  13361. };
  13362. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13363. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13364. // Not ready?
  13365. if (!texture) {
  13366. if (this._boundTexturesCache[channel] != null) {
  13367. this._activeChannel = channel;
  13368. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13369. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13370. if (this.webGLVersion > 1) {
  13371. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13372. }
  13373. }
  13374. return false;
  13375. }
  13376. // Video
  13377. if (texture.video) {
  13378. this._activeChannel = channel;
  13379. texture.update();
  13380. }
  13381. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13382. texture.delayLoad();
  13383. return false;
  13384. }
  13385. var internalTexture;
  13386. if (texture.isReady()) {
  13387. internalTexture = texture.getInternalTexture();
  13388. }
  13389. else if (texture.isCube) {
  13390. internalTexture = this.emptyCubeTexture;
  13391. }
  13392. else if (texture.is3D) {
  13393. internalTexture = this.emptyTexture3D;
  13394. }
  13395. else {
  13396. internalTexture = this.emptyTexture;
  13397. }
  13398. if (!isPartOfTextureArray) {
  13399. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13400. }
  13401. if (this._boundTexturesCache[channel] === internalTexture) {
  13402. this._moveBoundTextureOnTop(internalTexture);
  13403. if (!isPartOfTextureArray) {
  13404. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13405. }
  13406. return false;
  13407. }
  13408. this._activeChannel = channel;
  13409. if (internalTexture && internalTexture.is3D) {
  13410. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13411. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13412. internalTexture._cachedWrapU = texture.wrapU;
  13413. switch (texture.wrapU) {
  13414. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13415. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13416. break;
  13417. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13418. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13419. break;
  13420. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13421. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13422. break;
  13423. }
  13424. }
  13425. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13426. internalTexture._cachedWrapV = texture.wrapV;
  13427. switch (texture.wrapV) {
  13428. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13429. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13430. break;
  13431. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13432. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13433. break;
  13434. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13435. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13436. break;
  13437. }
  13438. }
  13439. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13440. internalTexture._cachedWrapR = texture.wrapR;
  13441. switch (texture.wrapV) {
  13442. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13443. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13444. break;
  13445. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13446. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13447. break;
  13448. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13449. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13450. break;
  13451. }
  13452. }
  13453. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13454. }
  13455. else if (internalTexture && internalTexture.isCube) {
  13456. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13457. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13458. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13459. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13460. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13461. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13462. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13463. }
  13464. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13465. }
  13466. else {
  13467. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13468. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13469. internalTexture._cachedWrapU = texture.wrapU;
  13470. switch (texture.wrapU) {
  13471. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13472. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13473. break;
  13474. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13475. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13476. break;
  13477. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13478. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13479. break;
  13480. }
  13481. }
  13482. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13483. internalTexture._cachedWrapV = texture.wrapV;
  13484. switch (texture.wrapV) {
  13485. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13486. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13487. break;
  13488. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13489. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13490. break;
  13491. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13492. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13493. break;
  13494. }
  13495. }
  13496. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13497. }
  13498. return true;
  13499. };
  13500. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13501. if (channel < 0 || !uniform) {
  13502. return;
  13503. }
  13504. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13505. this._textureUnits = new Int32Array(textures.length);
  13506. }
  13507. for (var i = 0; i < textures.length; i++) {
  13508. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13509. }
  13510. this._gl.uniform1iv(uniform, this._textureUnits);
  13511. for (var index = 0; index < textures.length; index++) {
  13512. this._setTexture(this._textureUnits[index], textures[index], true);
  13513. }
  13514. };
  13515. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13516. var internalTexture = texture.getInternalTexture();
  13517. if (!internalTexture) {
  13518. return;
  13519. }
  13520. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13521. var value = texture.anisotropicFilteringLevel;
  13522. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13523. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13524. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13525. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13526. }
  13527. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13528. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13529. internalTexture._cachedAnisotropicFilteringLevel = value;
  13530. }
  13531. };
  13532. Engine.prototype.readPixels = function (x, y, width, height) {
  13533. var data = new Uint8Array(height * width * 4);
  13534. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13535. return data;
  13536. };
  13537. /**
  13538. * Add an externaly attached data from its key.
  13539. * This method call will fail and return false, if such key already exists.
  13540. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13541. * @param key the unique key that identifies the data
  13542. * @param data the data object to associate to the key for this Engine instance
  13543. * @return true if no such key were already present and the data was added successfully, false otherwise
  13544. */
  13545. Engine.prototype.addExternalData = function (key, data) {
  13546. if (!this._externalData) {
  13547. this._externalData = new BABYLON.StringDictionary();
  13548. }
  13549. return this._externalData.add(key, data);
  13550. };
  13551. /**
  13552. * Get an externaly attached data from its key
  13553. * @param key the unique key that identifies the data
  13554. * @return the associated data, if present (can be null), or undefined if not present
  13555. */
  13556. Engine.prototype.getExternalData = function (key) {
  13557. if (!this._externalData) {
  13558. this._externalData = new BABYLON.StringDictionary();
  13559. }
  13560. return this._externalData.get(key);
  13561. };
  13562. /**
  13563. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13564. * @param key the unique key that identifies the data
  13565. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13566. * @return the associated data, can be null if the factory returned null.
  13567. */
  13568. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13569. if (!this._externalData) {
  13570. this._externalData = new BABYLON.StringDictionary();
  13571. }
  13572. return this._externalData.getOrAddWithFactory(key, factory);
  13573. };
  13574. /**
  13575. * Remove an externaly attached data from the Engine instance
  13576. * @param key the unique key that identifies the data
  13577. * @return true if the data was successfully removed, false if it doesn't exist
  13578. */
  13579. Engine.prototype.removeExternalData = function (key) {
  13580. if (!this._externalData) {
  13581. this._externalData = new BABYLON.StringDictionary();
  13582. }
  13583. return this._externalData.remove(key);
  13584. };
  13585. Engine.prototype.unbindAllAttributes = function () {
  13586. if (this._mustWipeVertexAttributes) {
  13587. this._mustWipeVertexAttributes = false;
  13588. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13589. this._gl.disableVertexAttribArray(i);
  13590. this._vertexAttribArraysEnabled[i] = false;
  13591. this._currentBufferPointers[i].active = false;
  13592. }
  13593. return;
  13594. }
  13595. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13596. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13597. continue;
  13598. }
  13599. this._gl.disableVertexAttribArray(i);
  13600. this._vertexAttribArraysEnabled[i] = false;
  13601. this._currentBufferPointers[i].active = false;
  13602. }
  13603. };
  13604. Engine.prototype.releaseEffects = function () {
  13605. for (var name in this._compiledEffects) {
  13606. this._deleteProgram(this._compiledEffects[name]._program);
  13607. }
  13608. this._compiledEffects = {};
  13609. };
  13610. // Dispose
  13611. Engine.prototype.dispose = function () {
  13612. this.hideLoadingUI();
  13613. this.stopRenderLoop();
  13614. // Release postProcesses
  13615. while (this.postProcesses.length) {
  13616. this.postProcesses[0].dispose();
  13617. }
  13618. // Empty texture
  13619. if (this._emptyTexture) {
  13620. this._releaseTexture(this._emptyTexture);
  13621. this._emptyTexture = null;
  13622. }
  13623. if (this._emptyCubeTexture) {
  13624. this._releaseTexture(this._emptyCubeTexture);
  13625. this._emptyCubeTexture = null;
  13626. }
  13627. // Rescale PP
  13628. if (this._rescalePostProcess) {
  13629. this._rescalePostProcess.dispose();
  13630. }
  13631. // Release scenes
  13632. while (this.scenes.length) {
  13633. this.scenes[0].dispose();
  13634. }
  13635. // Release audio engine
  13636. if (Engine.audioEngine) {
  13637. Engine.audioEngine.dispose();
  13638. }
  13639. // Release effects
  13640. this.releaseEffects();
  13641. // Unbind
  13642. this.unbindAllAttributes();
  13643. if (this._dummyFramebuffer) {
  13644. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13645. }
  13646. //WebVR
  13647. this.disableVR();
  13648. // Events
  13649. if (BABYLON.Tools.IsWindowObjectExist()) {
  13650. window.removeEventListener("blur", this._onBlur);
  13651. window.removeEventListener("focus", this._onFocus);
  13652. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13653. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13654. if (this._renderingCanvas) {
  13655. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13656. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13657. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13658. if (!this._doNotHandleContextLost) {
  13659. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13660. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13661. }
  13662. }
  13663. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13664. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13665. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13666. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13667. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13668. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13669. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13670. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13671. if (this._onVrDisplayConnect) {
  13672. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13673. if (this._onVrDisplayDisconnect) {
  13674. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13675. }
  13676. if (this._onVrDisplayPresentChange) {
  13677. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13678. }
  13679. this._onVrDisplayConnect = null;
  13680. this._onVrDisplayDisconnect = null;
  13681. }
  13682. }
  13683. // Remove from Instances
  13684. var index = Engine.Instances.indexOf(this);
  13685. if (index >= 0) {
  13686. Engine.Instances.splice(index, 1);
  13687. }
  13688. this._workingCanvas = null;
  13689. this._workingContext = null;
  13690. this._currentBufferPointers = [];
  13691. this._renderingCanvas = null;
  13692. this._currentProgram = null;
  13693. this.onResizeObservable.clear();
  13694. this.onCanvasBlurObservable.clear();
  13695. this.onCanvasFocusObservable.clear();
  13696. this.onCanvasPointerOutObservable.clear();
  13697. this.onBeginFrameObservable.clear();
  13698. this.onEndFrameObservable.clear();
  13699. BABYLON.Effect.ResetCache();
  13700. // Abort active requests
  13701. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13702. var request = _a[_i];
  13703. request.abort();
  13704. }
  13705. };
  13706. // Loading screen
  13707. Engine.prototype.displayLoadingUI = function () {
  13708. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13709. return;
  13710. }
  13711. var loadingScreen = this.loadingScreen;
  13712. if (loadingScreen) {
  13713. loadingScreen.displayLoadingUI();
  13714. }
  13715. };
  13716. Engine.prototype.hideLoadingUI = function () {
  13717. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13718. return;
  13719. }
  13720. var loadingScreen = this.loadingScreen;
  13721. if (loadingScreen) {
  13722. loadingScreen.hideLoadingUI();
  13723. }
  13724. };
  13725. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13726. get: function () {
  13727. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13728. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13729. return this._loadingScreen;
  13730. },
  13731. set: function (loadingScreen) {
  13732. this._loadingScreen = loadingScreen;
  13733. },
  13734. enumerable: true,
  13735. configurable: true
  13736. });
  13737. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13738. set: function (text) {
  13739. this.loadingScreen.loadingUIText = text;
  13740. },
  13741. enumerable: true,
  13742. configurable: true
  13743. });
  13744. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13745. set: function (color) {
  13746. this.loadingScreen.loadingUIBackgroundColor = color;
  13747. },
  13748. enumerable: true,
  13749. configurable: true
  13750. });
  13751. Engine.prototype.attachContextLostEvent = function (callback) {
  13752. if (this._renderingCanvas) {
  13753. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13754. }
  13755. };
  13756. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13757. if (this._renderingCanvas) {
  13758. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13759. }
  13760. };
  13761. Engine.prototype.getVertexShaderSource = function (program) {
  13762. var shaders = this._gl.getAttachedShaders(program);
  13763. if (!shaders) {
  13764. return null;
  13765. }
  13766. return this._gl.getShaderSource(shaders[0]);
  13767. };
  13768. Engine.prototype.getFragmentShaderSource = function (program) {
  13769. var shaders = this._gl.getAttachedShaders(program);
  13770. if (!shaders) {
  13771. return null;
  13772. }
  13773. return this._gl.getShaderSource(shaders[1]);
  13774. };
  13775. Engine.prototype.getError = function () {
  13776. return this._gl.getError();
  13777. };
  13778. // FPS
  13779. Engine.prototype.getFps = function () {
  13780. return this._fps;
  13781. };
  13782. Engine.prototype.getDeltaTime = function () {
  13783. return this._deltaTime;
  13784. };
  13785. Engine.prototype._measureFps = function () {
  13786. this._performanceMonitor.sampleFrame();
  13787. this._fps = this._performanceMonitor.averageFPS;
  13788. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13789. };
  13790. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13791. if (faceIndex === void 0) { faceIndex = -1; }
  13792. var gl = this._gl;
  13793. if (!this._dummyFramebuffer) {
  13794. var dummy = gl.createFramebuffer();
  13795. if (!dummy) {
  13796. throw new Error("Unable to create dummy framebuffer");
  13797. }
  13798. this._dummyFramebuffer = dummy;
  13799. }
  13800. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13801. if (faceIndex > -1) {
  13802. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13803. }
  13804. else {
  13805. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13806. }
  13807. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13808. var buffer;
  13809. switch (readType) {
  13810. case gl.UNSIGNED_BYTE:
  13811. buffer = new Uint8Array(4 * width * height);
  13812. readType = gl.UNSIGNED_BYTE;
  13813. break;
  13814. default:
  13815. buffer = new Float32Array(4 * width * height);
  13816. readType = gl.FLOAT;
  13817. break;
  13818. }
  13819. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13820. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13821. return buffer;
  13822. };
  13823. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13824. if (this._webGLVersion > 1) {
  13825. return this._caps.colorBufferFloat;
  13826. }
  13827. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13828. };
  13829. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13830. if (this._webGLVersion > 1) {
  13831. return this._caps.colorBufferFloat;
  13832. }
  13833. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13834. };
  13835. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13836. Engine.prototype._canRenderToFramebuffer = function (type) {
  13837. var gl = this._gl;
  13838. //clear existing errors
  13839. while (gl.getError() !== gl.NO_ERROR) { }
  13840. var successful = true;
  13841. var texture = gl.createTexture();
  13842. gl.bindTexture(gl.TEXTURE_2D, texture);
  13843. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13844. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13845. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13846. var fb = gl.createFramebuffer();
  13847. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13848. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13849. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13850. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13851. successful = successful && (gl.getError() === gl.NO_ERROR);
  13852. //try render by clearing frame buffer's color buffer
  13853. if (successful) {
  13854. gl.clear(gl.COLOR_BUFFER_BIT);
  13855. successful = successful && (gl.getError() === gl.NO_ERROR);
  13856. }
  13857. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13858. if (successful) {
  13859. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13860. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13861. var readFormat = gl.RGBA;
  13862. var readType = gl.UNSIGNED_BYTE;
  13863. var buffer = new Uint8Array(4);
  13864. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13865. successful = successful && (gl.getError() === gl.NO_ERROR);
  13866. }
  13867. //clean up
  13868. gl.deleteTexture(texture);
  13869. gl.deleteFramebuffer(fb);
  13870. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13871. //clear accumulated errors
  13872. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13873. return successful;
  13874. };
  13875. Engine.prototype._getWebGLTextureType = function (type) {
  13876. if (type === Engine.TEXTURETYPE_FLOAT) {
  13877. return this._gl.FLOAT;
  13878. }
  13879. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13880. // Add Half Float Constant.
  13881. return this._gl.HALF_FLOAT_OES;
  13882. }
  13883. return this._gl.UNSIGNED_BYTE;
  13884. };
  13885. ;
  13886. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13887. if (this._webGLVersion === 1) {
  13888. return this._gl.RGBA;
  13889. }
  13890. if (type === Engine.TEXTURETYPE_FLOAT) {
  13891. return this._gl.RGBA32F;
  13892. }
  13893. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13894. return this._gl.RGBA16F;
  13895. }
  13896. return this._gl.RGBA;
  13897. };
  13898. ;
  13899. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13900. if (type === Engine.TEXTURETYPE_FLOAT) {
  13901. return this._gl.RGBA32F;
  13902. }
  13903. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13904. return this._gl.RGBA16F;
  13905. }
  13906. return this._gl.RGBA8;
  13907. };
  13908. ;
  13909. Engine.prototype.createQuery = function () {
  13910. return this._gl.createQuery();
  13911. };
  13912. Engine.prototype.deleteQuery = function (query) {
  13913. this._gl.deleteQuery(query);
  13914. return this;
  13915. };
  13916. Engine.prototype.isQueryResultAvailable = function (query) {
  13917. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13918. };
  13919. Engine.prototype.getQueryResult = function (query) {
  13920. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13921. };
  13922. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13923. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13924. this._gl.beginQuery(glAlgorithm, query);
  13925. return this;
  13926. };
  13927. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13928. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13929. this._gl.endQuery(glAlgorithm);
  13930. return this;
  13931. };
  13932. /* Time queries */
  13933. Engine.prototype._createTimeQuery = function () {
  13934. var timerQuery = this._caps.timerQuery;
  13935. if (timerQuery.createQueryEXT) {
  13936. return timerQuery.createQueryEXT();
  13937. }
  13938. return this.createQuery();
  13939. };
  13940. Engine.prototype._deleteTimeQuery = function (query) {
  13941. var timerQuery = this._caps.timerQuery;
  13942. if (timerQuery.deleteQueryEXT) {
  13943. timerQuery.deleteQueryEXT(query);
  13944. return;
  13945. }
  13946. this.deleteQuery(query);
  13947. };
  13948. Engine.prototype._getTimeQueryResult = function (query) {
  13949. var timerQuery = this._caps.timerQuery;
  13950. if (timerQuery.getQueryObjectEXT) {
  13951. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13952. }
  13953. return this.getQueryResult(query);
  13954. };
  13955. Engine.prototype._getTimeQueryAvailability = function (query) {
  13956. var timerQuery = this._caps.timerQuery;
  13957. if (timerQuery.getQueryObjectEXT) {
  13958. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13959. }
  13960. return this.isQueryResultAvailable(query);
  13961. };
  13962. Engine.prototype.startTimeQuery = function () {
  13963. var timerQuery = this._caps.timerQuery;
  13964. if (!timerQuery) {
  13965. return null;
  13966. }
  13967. var token = new BABYLON._TimeToken();
  13968. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13969. if (this._caps.canUseTimestampForTimerQuery) {
  13970. token._startTimeQuery = this._createTimeQuery();
  13971. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13972. }
  13973. else {
  13974. if (this._currentNonTimestampToken) {
  13975. return this._currentNonTimestampToken;
  13976. }
  13977. token._timeElapsedQuery = this._createTimeQuery();
  13978. if (timerQuery.beginQueryEXT) {
  13979. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13980. }
  13981. else {
  13982. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13983. }
  13984. this._currentNonTimestampToken = token;
  13985. }
  13986. return token;
  13987. };
  13988. Engine.prototype.endTimeQuery = function (token) {
  13989. var timerQuery = this._caps.timerQuery;
  13990. if (!timerQuery || !token) {
  13991. return -1;
  13992. }
  13993. if (this._caps.canUseTimestampForTimerQuery) {
  13994. if (!token._startTimeQuery) {
  13995. return -1;
  13996. }
  13997. if (!token._endTimeQuery) {
  13998. token._endTimeQuery = this._createTimeQuery();
  13999. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14000. }
  14001. }
  14002. else if (!token._timeElapsedQueryEnded) {
  14003. if (!token._timeElapsedQuery) {
  14004. return -1;
  14005. }
  14006. if (timerQuery.endQueryEXT) {
  14007. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14008. }
  14009. else {
  14010. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14011. }
  14012. token._timeElapsedQueryEnded = true;
  14013. }
  14014. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14015. var available = false;
  14016. if (token._endTimeQuery) {
  14017. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14018. }
  14019. else if (token._timeElapsedQuery) {
  14020. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14021. }
  14022. if (available && !disjoint) {
  14023. var result = 0;
  14024. if (this._caps.canUseTimestampForTimerQuery) {
  14025. if (!token._startTimeQuery || !token._endTimeQuery) {
  14026. return -1;
  14027. }
  14028. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14029. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14030. result = timeEnd - timeStart;
  14031. this._deleteTimeQuery(token._startTimeQuery);
  14032. this._deleteTimeQuery(token._endTimeQuery);
  14033. token._startTimeQuery = null;
  14034. token._endTimeQuery = null;
  14035. }
  14036. else {
  14037. if (!token._timeElapsedQuery) {
  14038. return -1;
  14039. }
  14040. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14041. this._deleteTimeQuery(token._timeElapsedQuery);
  14042. token._timeElapsedQuery = null;
  14043. token._timeElapsedQueryEnded = false;
  14044. this._currentNonTimestampToken = null;
  14045. }
  14046. return result;
  14047. }
  14048. return -1;
  14049. };
  14050. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14051. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14052. };
  14053. // Transform feedback
  14054. Engine.prototype.createTransformFeedback = function () {
  14055. return this._gl.createTransformFeedback();
  14056. };
  14057. Engine.prototype.deleteTransformFeedback = function (value) {
  14058. this._gl.deleteTransformFeedback(value);
  14059. };
  14060. Engine.prototype.bindTransformFeedback = function (value) {
  14061. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14062. };
  14063. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14064. if (usePoints === void 0) { usePoints = true; }
  14065. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14066. };
  14067. Engine.prototype.endTransformFeedback = function () {
  14068. this._gl.endTransformFeedback();
  14069. };
  14070. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14071. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14072. };
  14073. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14074. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14075. };
  14076. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14077. var _this = this;
  14078. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14079. this._activeRequests.push(request);
  14080. request.onCompleteObservable.add(function (request) {
  14081. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14082. });
  14083. return request;
  14084. };
  14085. /** @ignore */
  14086. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14087. var _this = this;
  14088. return new Promise(function (resolve, reject) {
  14089. _this._loadFile(url, function (data) {
  14090. resolve(data);
  14091. }, undefined, database, useArrayBuffer, function (request, exception) {
  14092. reject(exception);
  14093. });
  14094. });
  14095. };
  14096. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14097. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14098. var onload = function (data) {
  14099. loadedFiles[index] = data;
  14100. loadedFiles._internalCount++;
  14101. if (loadedFiles._internalCount === 6) {
  14102. onfinish(loadedFiles);
  14103. }
  14104. };
  14105. var onerror = function (request, exception) {
  14106. if (onErrorCallBack && request) {
  14107. onErrorCallBack(request.status + " " + request.statusText, exception);
  14108. }
  14109. };
  14110. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14111. };
  14112. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14113. if (onError === void 0) { onError = null; }
  14114. var loadedFiles = [];
  14115. loadedFiles._internalCount = 0;
  14116. for (var index = 0; index < 6; index++) {
  14117. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14118. }
  14119. };
  14120. // Statics
  14121. Engine.isSupported = function () {
  14122. try {
  14123. var tempcanvas = document.createElement("canvas");
  14124. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14125. return gl != null && !!window.WebGLRenderingContext;
  14126. }
  14127. catch (e) {
  14128. return false;
  14129. }
  14130. };
  14131. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14132. Engine.ExceptionList = [
  14133. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14134. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14135. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14136. ];
  14137. Engine.Instances = new Array();
  14138. // Const statics
  14139. Engine._ALPHA_DISABLE = 0;
  14140. Engine._ALPHA_ADD = 1;
  14141. Engine._ALPHA_COMBINE = 2;
  14142. Engine._ALPHA_SUBTRACT = 3;
  14143. Engine._ALPHA_MULTIPLY = 4;
  14144. Engine._ALPHA_MAXIMIZED = 5;
  14145. Engine._ALPHA_ONEONE = 6;
  14146. Engine._ALPHA_PREMULTIPLIED = 7;
  14147. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14148. Engine._ALPHA_INTERPOLATE = 9;
  14149. Engine._ALPHA_SCREENMODE = 10;
  14150. Engine._DELAYLOADSTATE_NONE = 0;
  14151. Engine._DELAYLOADSTATE_LOADED = 1;
  14152. Engine._DELAYLOADSTATE_LOADING = 2;
  14153. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14154. Engine._TEXTUREFORMAT_ALPHA = 0;
  14155. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14156. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14157. Engine._TEXTUREFORMAT_RGB = 4;
  14158. Engine._TEXTUREFORMAT_RGBA = 5;
  14159. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14160. Engine._TEXTURETYPE_FLOAT = 1;
  14161. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14162. // Depht or Stencil test Constants.
  14163. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14164. 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.
  14165. 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.
  14166. 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.
  14167. 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.
  14168. 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.
  14169. 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.
  14170. 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.
  14171. // Stencil Actions Constants.
  14172. Engine._KEEP = 0x1E00;
  14173. Engine._REPLACE = 0x1E01;
  14174. Engine._INCR = 0x1E02;
  14175. Engine._DECR = 0x1E03;
  14176. Engine._INVERT = 0x150A;
  14177. Engine._INCR_WRAP = 0x8507;
  14178. Engine._DECR_WRAP = 0x8508;
  14179. // Texture rescaling mode
  14180. Engine._SCALEMODE_FLOOR = 1;
  14181. Engine._SCALEMODE_NEAREST = 2;
  14182. Engine._SCALEMODE_CEILING = 3;
  14183. // Updatable statics so stick with vars here
  14184. Engine.CollisionsEpsilon = 0.001;
  14185. Engine.CodeRepository = "src/";
  14186. Engine.ShadersRepository = "src/Shaders/";
  14187. return Engine;
  14188. }());
  14189. BABYLON.Engine = Engine;
  14190. })(BABYLON || (BABYLON = {}));
  14191. //# sourceMappingURL=babylon.engine.js.map
  14192. var BABYLON;
  14193. (function (BABYLON) {
  14194. /**
  14195. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14196. */
  14197. var Node = /** @class */ (function () {
  14198. /**
  14199. * @constructor
  14200. * @param {string} name - the name and id to be given to this node
  14201. * @param {BABYLON.Scene} the scene this node will be added to
  14202. */
  14203. function Node(name, scene) {
  14204. if (scene === void 0) { scene = null; }
  14205. this.state = "";
  14206. this.metadata = null;
  14207. this.doNotSerialize = false;
  14208. this.animations = new Array();
  14209. this._ranges = {};
  14210. this._isEnabled = true;
  14211. this._isReady = true;
  14212. this._currentRenderId = -1;
  14213. this._parentRenderId = -1;
  14214. /**
  14215. * An event triggered when the mesh is disposed.
  14216. * @type {BABYLON.Observable}
  14217. */
  14218. this.onDisposeObservable = new BABYLON.Observable();
  14219. // Behaviors
  14220. this._behaviors = new Array();
  14221. this.name = name;
  14222. this.id = name;
  14223. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14224. this.uniqueId = this._scene.getUniqueId();
  14225. this._initCache();
  14226. }
  14227. Object.defineProperty(Node.prototype, "parent", {
  14228. get: function () {
  14229. return this._parentNode;
  14230. },
  14231. set: function (parent) {
  14232. if (this._parentNode === parent) {
  14233. return;
  14234. }
  14235. // Remove self from list of children of parent
  14236. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14237. var index = this._parentNode._children.indexOf(this);
  14238. if (index !== -1) {
  14239. this._parentNode._children.splice(index, 1);
  14240. }
  14241. }
  14242. // Store new parent
  14243. this._parentNode = parent;
  14244. // Add as child to new parent
  14245. if (this._parentNode) {
  14246. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14247. this._parentNode._children = new Array();
  14248. }
  14249. this._parentNode._children.push(this);
  14250. }
  14251. },
  14252. enumerable: true,
  14253. configurable: true
  14254. });
  14255. Node.prototype.getClassName = function () {
  14256. return "Node";
  14257. };
  14258. Object.defineProperty(Node.prototype, "onDispose", {
  14259. set: function (callback) {
  14260. if (this._onDisposeObserver) {
  14261. this.onDisposeObservable.remove(this._onDisposeObserver);
  14262. }
  14263. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14264. },
  14265. enumerable: true,
  14266. configurable: true
  14267. });
  14268. Node.prototype.getScene = function () {
  14269. return this._scene;
  14270. };
  14271. Node.prototype.getEngine = function () {
  14272. return this._scene.getEngine();
  14273. };
  14274. Node.prototype.addBehavior = function (behavior) {
  14275. var _this = this;
  14276. var index = this._behaviors.indexOf(behavior);
  14277. if (index !== -1) {
  14278. return this;
  14279. }
  14280. behavior.init();
  14281. if (this._scene.isLoading) {
  14282. // We defer the attach when the scene will be loaded
  14283. var observer = this._scene.onDataLoadedObservable.add(function () {
  14284. behavior.attach(_this);
  14285. setTimeout(function () {
  14286. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14287. _this._scene.onDataLoadedObservable.remove(observer);
  14288. }, 0);
  14289. });
  14290. }
  14291. else {
  14292. behavior.attach(this);
  14293. }
  14294. this._behaviors.push(behavior);
  14295. return this;
  14296. };
  14297. Node.prototype.removeBehavior = function (behavior) {
  14298. var index = this._behaviors.indexOf(behavior);
  14299. if (index === -1) {
  14300. return this;
  14301. }
  14302. this._behaviors[index].detach();
  14303. this._behaviors.splice(index, 1);
  14304. return this;
  14305. };
  14306. Object.defineProperty(Node.prototype, "behaviors", {
  14307. get: function () {
  14308. return this._behaviors;
  14309. },
  14310. enumerable: true,
  14311. configurable: true
  14312. });
  14313. Node.prototype.getBehaviorByName = function (name) {
  14314. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14315. var behavior = _a[_i];
  14316. if (behavior.name === name) {
  14317. return behavior;
  14318. }
  14319. }
  14320. return null;
  14321. };
  14322. // override it in derived class
  14323. Node.prototype.getWorldMatrix = function () {
  14324. return BABYLON.Matrix.Identity();
  14325. };
  14326. // override it in derived class if you add new variables to the cache
  14327. // and call the parent class method
  14328. Node.prototype._initCache = function () {
  14329. this._cache = {};
  14330. this._cache.parent = undefined;
  14331. };
  14332. Node.prototype.updateCache = function (force) {
  14333. if (!force && this.isSynchronized())
  14334. return;
  14335. this._cache.parent = this.parent;
  14336. this._updateCache();
  14337. };
  14338. // override it in derived class if you add new variables to the cache
  14339. // and call the parent class method if !ignoreParentClass
  14340. Node.prototype._updateCache = function (ignoreParentClass) {
  14341. };
  14342. // override it in derived class if you add new variables to the cache
  14343. Node.prototype._isSynchronized = function () {
  14344. return true;
  14345. };
  14346. Node.prototype._markSyncedWithParent = function () {
  14347. if (this.parent) {
  14348. this._parentRenderId = this.parent._currentRenderId;
  14349. }
  14350. };
  14351. Node.prototype.isSynchronizedWithParent = function () {
  14352. if (!this.parent) {
  14353. return true;
  14354. }
  14355. if (this._parentRenderId !== this.parent._currentRenderId) {
  14356. return false;
  14357. }
  14358. return this.parent.isSynchronized();
  14359. };
  14360. Node.prototype.isSynchronized = function (updateCache) {
  14361. var check = this.hasNewParent();
  14362. check = check || !this.isSynchronizedWithParent();
  14363. check = check || !this._isSynchronized();
  14364. if (updateCache)
  14365. this.updateCache(true);
  14366. return !check;
  14367. };
  14368. Node.prototype.hasNewParent = function (update) {
  14369. if (this._cache.parent === this.parent)
  14370. return false;
  14371. if (update)
  14372. this._cache.parent = this.parent;
  14373. return true;
  14374. };
  14375. /**
  14376. * Is this node ready to be used/rendered
  14377. * @return {boolean} is it ready
  14378. */
  14379. Node.prototype.isReady = function () {
  14380. return this._isReady;
  14381. };
  14382. /**
  14383. * Is this node enabled.
  14384. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
  14385. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  14386. * @return {boolean} whether this node (and its parent) is enabled.
  14387. * @see setEnabled
  14388. */
  14389. Node.prototype.isEnabled = function (checkAncestors) {
  14390. if (checkAncestors === void 0) { checkAncestors = true; }
  14391. if (checkAncestors === false) {
  14392. return this._isEnabled;
  14393. }
  14394. if (this._isEnabled === false) {
  14395. return false;
  14396. }
  14397. if (this.parent !== undefined && this.parent !== null) {
  14398. return this.parent.isEnabled(checkAncestors);
  14399. }
  14400. return true;
  14401. };
  14402. /**
  14403. * Set the enabled state of this node.
  14404. * @param {boolean} value - the new enabled state
  14405. * @see isEnabled
  14406. */
  14407. Node.prototype.setEnabled = function (value) {
  14408. this._isEnabled = value;
  14409. };
  14410. /**
  14411. * Is this node a descendant of the given node.
  14412. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14413. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14414. * @see parent
  14415. */
  14416. Node.prototype.isDescendantOf = function (ancestor) {
  14417. if (this.parent) {
  14418. if (this.parent === ancestor) {
  14419. return true;
  14420. }
  14421. return this.parent.isDescendantOf(ancestor);
  14422. }
  14423. return false;
  14424. };
  14425. /**
  14426. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14427. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14428. * @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.
  14429. * @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.
  14430. */
  14431. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14432. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14433. if (!this._children) {
  14434. return;
  14435. }
  14436. for (var index = 0; index < this._children.length; index++) {
  14437. var item = this._children[index];
  14438. if (!predicate || predicate(item)) {
  14439. results.push(item);
  14440. }
  14441. if (!directDescendantsOnly) {
  14442. item._getDescendants(results, false, predicate);
  14443. }
  14444. }
  14445. };
  14446. /**
  14447. * Will return all nodes that have this node as ascendant.
  14448. * @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.
  14449. * @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.
  14450. * @return {BABYLON.Node[]} all children nodes of all types.
  14451. */
  14452. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14453. var results = new Array();
  14454. this._getDescendants(results, directDescendantsOnly, predicate);
  14455. return results;
  14456. };
  14457. /**
  14458. * Get all child-meshes of this node.
  14459. */
  14460. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14461. var results = [];
  14462. this._getDescendants(results, directDescendantsOnly, function (node) {
  14463. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14464. });
  14465. return results;
  14466. };
  14467. /**
  14468. * Get all child-transformNodes of this node.
  14469. */
  14470. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14471. var results = [];
  14472. this._getDescendants(results, directDescendantsOnly, function (node) {
  14473. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14474. });
  14475. return results;
  14476. };
  14477. /**
  14478. * Get all direct children of this node.
  14479. */
  14480. Node.prototype.getChildren = function (predicate) {
  14481. return this.getDescendants(true, predicate);
  14482. };
  14483. Node.prototype._setReady = function (state) {
  14484. if (state === this._isReady) {
  14485. return;
  14486. }
  14487. if (!state) {
  14488. this._isReady = false;
  14489. return;
  14490. }
  14491. this._isReady = true;
  14492. if (this.onReady) {
  14493. this.onReady(this);
  14494. }
  14495. };
  14496. Node.prototype.getAnimationByName = function (name) {
  14497. for (var i = 0; i < this.animations.length; i++) {
  14498. var animation = this.animations[i];
  14499. if (animation.name === name) {
  14500. return animation;
  14501. }
  14502. }
  14503. return null;
  14504. };
  14505. Node.prototype.createAnimationRange = function (name, from, to) {
  14506. // check name not already in use
  14507. if (!this._ranges[name]) {
  14508. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14509. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14510. if (this.animations[i]) {
  14511. this.animations[i].createRange(name, from, to);
  14512. }
  14513. }
  14514. }
  14515. };
  14516. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14517. if (deleteFrames === void 0) { deleteFrames = true; }
  14518. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14519. if (this.animations[i]) {
  14520. this.animations[i].deleteRange(name, deleteFrames);
  14521. }
  14522. }
  14523. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14524. };
  14525. Node.prototype.getAnimationRange = function (name) {
  14526. return this._ranges[name];
  14527. };
  14528. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14529. var range = this.getAnimationRange(name);
  14530. if (!range) {
  14531. return;
  14532. }
  14533. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14534. };
  14535. Node.prototype.serializeAnimationRanges = function () {
  14536. var serializationRanges = [];
  14537. for (var name in this._ranges) {
  14538. var localRange = this._ranges[name];
  14539. if (!localRange) {
  14540. continue;
  14541. }
  14542. var range = {};
  14543. range.name = name;
  14544. range.from = localRange.from;
  14545. range.to = localRange.to;
  14546. serializationRanges.push(range);
  14547. }
  14548. return serializationRanges;
  14549. };
  14550. // override it in derived class
  14551. Node.prototype.computeWorldMatrix = function (force) {
  14552. return BABYLON.Matrix.Identity();
  14553. };
  14554. Node.prototype.dispose = function () {
  14555. this.parent = null;
  14556. // Callback
  14557. this.onDisposeObservable.notifyObservers(this);
  14558. this.onDisposeObservable.clear();
  14559. // Behaviors
  14560. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14561. var behavior = _a[_i];
  14562. behavior.detach();
  14563. }
  14564. this._behaviors = [];
  14565. };
  14566. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14567. if (parsedNode.ranges) {
  14568. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14569. var data = parsedNode.ranges[index];
  14570. node.createAnimationRange(data.name, data.from, data.to);
  14571. }
  14572. }
  14573. };
  14574. __decorate([
  14575. BABYLON.serialize()
  14576. ], Node.prototype, "name", void 0);
  14577. __decorate([
  14578. BABYLON.serialize()
  14579. ], Node.prototype, "id", void 0);
  14580. __decorate([
  14581. BABYLON.serialize()
  14582. ], Node.prototype, "uniqueId", void 0);
  14583. __decorate([
  14584. BABYLON.serialize()
  14585. ], Node.prototype, "state", void 0);
  14586. __decorate([
  14587. BABYLON.serialize()
  14588. ], Node.prototype, "metadata", void 0);
  14589. return Node;
  14590. }());
  14591. BABYLON.Node = Node;
  14592. })(BABYLON || (BABYLON = {}));
  14593. //# sourceMappingURL=babylon.node.js.map
  14594. var BABYLON;
  14595. (function (BABYLON) {
  14596. var BoundingSphere = /** @class */ (function () {
  14597. function BoundingSphere(minimum, maximum) {
  14598. this.minimum = minimum;
  14599. this.maximum = maximum;
  14600. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14601. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14602. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14603. this.radius = distance * 0.5;
  14604. this.centerWorld = BABYLON.Vector3.Zero();
  14605. this._update(BABYLON.Matrix.Identity());
  14606. }
  14607. // Methods
  14608. BoundingSphere.prototype._update = function (world) {
  14609. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14610. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14611. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14612. };
  14613. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14614. for (var i = 0; i < 6; i++) {
  14615. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14616. return false;
  14617. }
  14618. return true;
  14619. };
  14620. BoundingSphere.prototype.intersectsPoint = function (point) {
  14621. var x = this.centerWorld.x - point.x;
  14622. var y = this.centerWorld.y - point.y;
  14623. var z = this.centerWorld.z - point.z;
  14624. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14625. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14626. return false;
  14627. return true;
  14628. };
  14629. // Statics
  14630. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14631. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14632. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14633. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14634. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14635. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14636. return false;
  14637. return true;
  14638. };
  14639. return BoundingSphere;
  14640. }());
  14641. BABYLON.BoundingSphere = BoundingSphere;
  14642. })(BABYLON || (BABYLON = {}));
  14643. //# sourceMappingURL=babylon.boundingSphere.js.map
  14644. var BABYLON;
  14645. (function (BABYLON) {
  14646. var BoundingBox = /** @class */ (function () {
  14647. function BoundingBox(minimum, maximum) {
  14648. this.minimum = minimum;
  14649. this.maximum = maximum;
  14650. this.vectors = new Array();
  14651. this.vectorsWorld = new Array();
  14652. // Bounding vectors
  14653. this.vectors.push(this.minimum.clone());
  14654. this.vectors.push(this.maximum.clone());
  14655. this.vectors.push(this.minimum.clone());
  14656. this.vectors[2].x = this.maximum.x;
  14657. this.vectors.push(this.minimum.clone());
  14658. this.vectors[3].y = this.maximum.y;
  14659. this.vectors.push(this.minimum.clone());
  14660. this.vectors[4].z = this.maximum.z;
  14661. this.vectors.push(this.maximum.clone());
  14662. this.vectors[5].z = this.minimum.z;
  14663. this.vectors.push(this.maximum.clone());
  14664. this.vectors[6].x = this.minimum.x;
  14665. this.vectors.push(this.maximum.clone());
  14666. this.vectors[7].y = this.minimum.y;
  14667. // OBB
  14668. this.center = this.maximum.add(this.minimum).scale(0.5);
  14669. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14670. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14671. // World
  14672. for (var index = 0; index < this.vectors.length; index++) {
  14673. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14674. }
  14675. this.minimumWorld = BABYLON.Vector3.Zero();
  14676. this.maximumWorld = BABYLON.Vector3.Zero();
  14677. this.centerWorld = BABYLON.Vector3.Zero();
  14678. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14679. this._update(BABYLON.Matrix.Identity());
  14680. }
  14681. // Methods
  14682. BoundingBox.prototype.getWorldMatrix = function () {
  14683. return this._worldMatrix;
  14684. };
  14685. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14686. this._worldMatrix.copyFrom(matrix);
  14687. return this;
  14688. };
  14689. BoundingBox.prototype._update = function (world) {
  14690. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14691. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14692. for (var index = 0; index < this.vectors.length; index++) {
  14693. var v = this.vectorsWorld[index];
  14694. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14695. if (v.x < this.minimumWorld.x)
  14696. this.minimumWorld.x = v.x;
  14697. if (v.y < this.minimumWorld.y)
  14698. this.minimumWorld.y = v.y;
  14699. if (v.z < this.minimumWorld.z)
  14700. this.minimumWorld.z = v.z;
  14701. if (v.x > this.maximumWorld.x)
  14702. this.maximumWorld.x = v.x;
  14703. if (v.y > this.maximumWorld.y)
  14704. this.maximumWorld.y = v.y;
  14705. if (v.z > this.maximumWorld.z)
  14706. this.maximumWorld.z = v.z;
  14707. }
  14708. // Extend
  14709. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14710. this.extendSizeWorld.scaleInPlace(0.5);
  14711. // OBB
  14712. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14713. this.centerWorld.scaleInPlace(0.5);
  14714. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14715. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14716. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14717. this._worldMatrix = world;
  14718. };
  14719. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14720. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14721. };
  14722. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14723. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14724. };
  14725. BoundingBox.prototype.intersectsPoint = function (point) {
  14726. var delta = -BABYLON.Epsilon;
  14727. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14728. return false;
  14729. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14730. return false;
  14731. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14732. return false;
  14733. return true;
  14734. };
  14735. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14736. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14737. };
  14738. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14739. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14740. return false;
  14741. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14742. return false;
  14743. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14744. return false;
  14745. return true;
  14746. };
  14747. // Statics
  14748. BoundingBox.Intersects = function (box0, box1) {
  14749. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14750. return false;
  14751. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14752. return false;
  14753. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14754. return false;
  14755. return true;
  14756. };
  14757. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14758. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14759. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14760. return (num <= (sphereRadius * sphereRadius));
  14761. };
  14762. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14763. for (var p = 0; p < 6; p++) {
  14764. for (var i = 0; i < 8; i++) {
  14765. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14766. return false;
  14767. }
  14768. }
  14769. }
  14770. return true;
  14771. };
  14772. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14773. for (var p = 0; p < 6; p++) {
  14774. var inCount = 8;
  14775. for (var i = 0; i < 8; i++) {
  14776. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14777. --inCount;
  14778. }
  14779. else {
  14780. break;
  14781. }
  14782. }
  14783. if (inCount === 0)
  14784. return false;
  14785. }
  14786. return true;
  14787. };
  14788. return BoundingBox;
  14789. }());
  14790. BABYLON.BoundingBox = BoundingBox;
  14791. })(BABYLON || (BABYLON = {}));
  14792. //# sourceMappingURL=babylon.boundingBox.js.map
  14793. var BABYLON;
  14794. (function (BABYLON) {
  14795. var computeBoxExtents = function (axis, box) {
  14796. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14797. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14798. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14799. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14800. var r = r0 + r1 + r2;
  14801. return {
  14802. min: p - r,
  14803. max: p + r
  14804. };
  14805. };
  14806. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14807. var axisOverlap = function (axis, box0, box1) {
  14808. var result0 = computeBoxExtents(axis, box0);
  14809. var result1 = computeBoxExtents(axis, box1);
  14810. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14811. };
  14812. var BoundingInfo = /** @class */ (function () {
  14813. function BoundingInfo(minimum, maximum) {
  14814. this.minimum = minimum;
  14815. this.maximum = maximum;
  14816. this._isLocked = false;
  14817. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14818. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14819. }
  14820. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14821. get: function () {
  14822. return this._isLocked;
  14823. },
  14824. set: function (value) {
  14825. this._isLocked = value;
  14826. },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. // Methods
  14831. BoundingInfo.prototype.update = function (world) {
  14832. if (this._isLocked) {
  14833. return;
  14834. }
  14835. this.boundingBox._update(world);
  14836. this.boundingSphere._update(world);
  14837. };
  14838. /**
  14839. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14840. * @param center New center of the bounding info
  14841. * @param extend New extend of the bounding info
  14842. */
  14843. BoundingInfo.prototype.centerOn = function (center, extend) {
  14844. this.minimum = center.subtract(extend);
  14845. this.maximum = center.add(extend);
  14846. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14847. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14848. return this;
  14849. };
  14850. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14851. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14852. return false;
  14853. return this.boundingBox.isInFrustum(frustumPlanes);
  14854. };
  14855. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14856. /**
  14857. * Gets the world distance between the min and max points of the bounding box
  14858. */
  14859. get: function () {
  14860. var boundingBox = this.boundingBox;
  14861. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14862. return size.length();
  14863. },
  14864. enumerable: true,
  14865. configurable: true
  14866. });
  14867. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14868. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14869. };
  14870. BoundingInfo.prototype._checkCollision = function (collider) {
  14871. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14872. };
  14873. BoundingInfo.prototype.intersectsPoint = function (point) {
  14874. if (!this.boundingSphere.centerWorld) {
  14875. return false;
  14876. }
  14877. if (!this.boundingSphere.intersectsPoint(point)) {
  14878. return false;
  14879. }
  14880. if (!this.boundingBox.intersectsPoint(point)) {
  14881. return false;
  14882. }
  14883. return true;
  14884. };
  14885. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14886. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14887. return false;
  14888. }
  14889. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14890. return false;
  14891. }
  14892. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14893. return false;
  14894. }
  14895. if (!precise) {
  14896. return true;
  14897. }
  14898. var box0 = this.boundingBox;
  14899. var box1 = boundingInfo.boundingBox;
  14900. if (!axisOverlap(box0.directions[0], box0, box1))
  14901. return false;
  14902. if (!axisOverlap(box0.directions[1], box0, box1))
  14903. return false;
  14904. if (!axisOverlap(box0.directions[2], box0, box1))
  14905. return false;
  14906. if (!axisOverlap(box1.directions[0], box0, box1))
  14907. return false;
  14908. if (!axisOverlap(box1.directions[1], box0, box1))
  14909. return false;
  14910. if (!axisOverlap(box1.directions[2], box0, box1))
  14911. return false;
  14912. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14913. return false;
  14914. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14915. return false;
  14916. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14917. return false;
  14918. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14919. return false;
  14920. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14921. return false;
  14922. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14923. return false;
  14924. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14925. return false;
  14926. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14927. return false;
  14928. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14929. return false;
  14930. return true;
  14931. };
  14932. return BoundingInfo;
  14933. }());
  14934. BABYLON.BoundingInfo = BoundingInfo;
  14935. })(BABYLON || (BABYLON = {}));
  14936. //# sourceMappingURL=babylon.boundingInfo.js.map
  14937. var BABYLON;
  14938. (function (BABYLON) {
  14939. var TransformNode = /** @class */ (function (_super) {
  14940. __extends(TransformNode, _super);
  14941. function TransformNode(name, scene, isPure) {
  14942. if (scene === void 0) { scene = null; }
  14943. if (isPure === void 0) { isPure = true; }
  14944. var _this = _super.call(this, name, scene) || this;
  14945. // Properties
  14946. _this._rotation = BABYLON.Vector3.Zero();
  14947. _this._scaling = BABYLON.Vector3.One();
  14948. _this._isDirty = false;
  14949. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14950. _this.scalingDeterminant = 1;
  14951. _this.infiniteDistance = false;
  14952. _this.position = BABYLON.Vector3.Zero();
  14953. _this._localWorld = BABYLON.Matrix.Zero();
  14954. _this._worldMatrix = BABYLON.Matrix.Zero();
  14955. _this._worldMatrixDeterminant = 0;
  14956. _this._absolutePosition = BABYLON.Vector3.Zero();
  14957. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14958. _this._postMultiplyPivotMatrix = false;
  14959. _this._isWorldMatrixFrozen = false;
  14960. /**
  14961. * An event triggered after the world matrix is updated
  14962. * @type {BABYLON.Observable}
  14963. */
  14964. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14965. _this._nonUniformScaling = false;
  14966. if (isPure) {
  14967. _this.getScene().addTransformNode(_this);
  14968. }
  14969. return _this;
  14970. }
  14971. Object.defineProperty(TransformNode.prototype, "rotation", {
  14972. /**
  14973. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14974. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14975. * Default : (0.0, 0.0, 0.0)
  14976. */
  14977. get: function () {
  14978. return this._rotation;
  14979. },
  14980. set: function (newRotation) {
  14981. this._rotation = newRotation;
  14982. },
  14983. enumerable: true,
  14984. configurable: true
  14985. });
  14986. Object.defineProperty(TransformNode.prototype, "scaling", {
  14987. /**
  14988. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14989. * Default : (1.0, 1.0, 1.0)
  14990. */
  14991. get: function () {
  14992. return this._scaling;
  14993. },
  14994. /**
  14995. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14996. * Default : (1.0, 1.0, 1.0)
  14997. */
  14998. set: function (newScaling) {
  14999. this._scaling = newScaling;
  15000. },
  15001. enumerable: true,
  15002. configurable: true
  15003. });
  15004. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15005. /**
  15006. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15007. * It's null by default.
  15008. * 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)
  15009. */
  15010. get: function () {
  15011. return this._rotationQuaternion;
  15012. },
  15013. set: function (quaternion) {
  15014. this._rotationQuaternion = quaternion;
  15015. //reset the rotation vector.
  15016. if (quaternion && this.rotation.length()) {
  15017. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15018. }
  15019. },
  15020. enumerable: true,
  15021. configurable: true
  15022. });
  15023. /**
  15024. * Returns the latest update of the World matrix
  15025. * Returns a Matrix.
  15026. */
  15027. TransformNode.prototype.getWorldMatrix = function () {
  15028. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15029. this.computeWorldMatrix();
  15030. }
  15031. return this._worldMatrix;
  15032. };
  15033. /**
  15034. * Returns the latest update of the World matrix determinant.
  15035. */
  15036. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15037. return this._worldMatrixDeterminant;
  15038. };
  15039. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15040. /**
  15041. * Returns directly the latest state of the mesh World matrix.
  15042. * A Matrix is returned.
  15043. */
  15044. get: function () {
  15045. return this._worldMatrix;
  15046. },
  15047. enumerable: true,
  15048. configurable: true
  15049. });
  15050. /**
  15051. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15052. * Returns the AbstractMesh.
  15053. */
  15054. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15055. this._poseMatrix.copyFrom(matrix);
  15056. return this;
  15057. };
  15058. /**
  15059. * Returns the mesh Pose matrix.
  15060. * Returned object : Matrix
  15061. */
  15062. TransformNode.prototype.getPoseMatrix = function () {
  15063. return this._poseMatrix;
  15064. };
  15065. TransformNode.prototype._isSynchronized = function () {
  15066. if (this._isDirty) {
  15067. return false;
  15068. }
  15069. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15070. return false;
  15071. if (this._cache.pivotMatrixUpdated) {
  15072. return false;
  15073. }
  15074. if (this.infiniteDistance) {
  15075. return false;
  15076. }
  15077. if (!this._cache.position.equals(this.position))
  15078. return false;
  15079. if (this.rotationQuaternion) {
  15080. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15081. return false;
  15082. }
  15083. if (!this._cache.rotation.equals(this.rotation))
  15084. return false;
  15085. if (!this._cache.scaling.equals(this.scaling))
  15086. return false;
  15087. return true;
  15088. };
  15089. TransformNode.prototype._initCache = function () {
  15090. _super.prototype._initCache.call(this);
  15091. this._cache.localMatrixUpdated = false;
  15092. this._cache.position = BABYLON.Vector3.Zero();
  15093. this._cache.scaling = BABYLON.Vector3.Zero();
  15094. this._cache.rotation = BABYLON.Vector3.Zero();
  15095. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15096. this._cache.billboardMode = -1;
  15097. };
  15098. TransformNode.prototype.markAsDirty = function (property) {
  15099. if (property === "rotation") {
  15100. this.rotationQuaternion = null;
  15101. }
  15102. this._currentRenderId = Number.MAX_VALUE;
  15103. this._isDirty = true;
  15104. return this;
  15105. };
  15106. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15107. /**
  15108. * Returns the current mesh absolute position.
  15109. * Retuns a Vector3.
  15110. */
  15111. get: function () {
  15112. return this._absolutePosition;
  15113. },
  15114. enumerable: true,
  15115. configurable: true
  15116. });
  15117. /**
  15118. * Sets a new pivot matrix to the mesh.
  15119. * Returns the AbstractMesh.
  15120. */
  15121. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15122. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  15123. this._pivotMatrix = matrix.clone();
  15124. this._cache.pivotMatrixUpdated = true;
  15125. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15126. if (this._postMultiplyPivotMatrix) {
  15127. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  15128. }
  15129. return this;
  15130. };
  15131. /**
  15132. * Returns the mesh pivot matrix.
  15133. * Default : Identity.
  15134. * A Matrix is returned.
  15135. */
  15136. TransformNode.prototype.getPivotMatrix = function () {
  15137. return this._pivotMatrix;
  15138. };
  15139. /**
  15140. * Prevents the World matrix to be computed any longer.
  15141. * Returns the AbstractMesh.
  15142. */
  15143. TransformNode.prototype.freezeWorldMatrix = function () {
  15144. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15145. this.computeWorldMatrix(true);
  15146. this._isWorldMatrixFrozen = true;
  15147. return this;
  15148. };
  15149. /**
  15150. * Allows back the World matrix computation.
  15151. * Returns the AbstractMesh.
  15152. */
  15153. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15154. this._isWorldMatrixFrozen = false;
  15155. this.computeWorldMatrix(true);
  15156. return this;
  15157. };
  15158. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15159. /**
  15160. * True if the World matrix has been frozen.
  15161. * Returns a boolean.
  15162. */
  15163. get: function () {
  15164. return this._isWorldMatrixFrozen;
  15165. },
  15166. enumerable: true,
  15167. configurable: true
  15168. });
  15169. /**
  15170. * Retuns the mesh absolute position in the World.
  15171. * Returns a Vector3.
  15172. */
  15173. TransformNode.prototype.getAbsolutePosition = function () {
  15174. this.computeWorldMatrix();
  15175. return this._absolutePosition;
  15176. };
  15177. /**
  15178. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15179. * Returns the AbstractMesh.
  15180. */
  15181. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15182. if (!absolutePosition) {
  15183. return this;
  15184. }
  15185. var absolutePositionX;
  15186. var absolutePositionY;
  15187. var absolutePositionZ;
  15188. if (absolutePosition.x === undefined) {
  15189. if (arguments.length < 3) {
  15190. return this;
  15191. }
  15192. absolutePositionX = arguments[0];
  15193. absolutePositionY = arguments[1];
  15194. absolutePositionZ = arguments[2];
  15195. }
  15196. else {
  15197. absolutePositionX = absolutePosition.x;
  15198. absolutePositionY = absolutePosition.y;
  15199. absolutePositionZ = absolutePosition.z;
  15200. }
  15201. if (this.parent) {
  15202. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15203. invertParentWorldMatrix.invert();
  15204. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15205. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15206. }
  15207. else {
  15208. this.position.x = absolutePositionX;
  15209. this.position.y = absolutePositionY;
  15210. this.position.z = absolutePositionZ;
  15211. }
  15212. return this;
  15213. };
  15214. /**
  15215. * Sets the mesh position in its local space.
  15216. * Returns the AbstractMesh.
  15217. */
  15218. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15219. this.computeWorldMatrix();
  15220. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15221. return this;
  15222. };
  15223. /**
  15224. * Returns the mesh position in the local space from the current World matrix values.
  15225. * Returns a new Vector3.
  15226. */
  15227. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15228. this.computeWorldMatrix();
  15229. var invLocalWorldMatrix = this._localWorld.clone();
  15230. invLocalWorldMatrix.invert();
  15231. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15232. };
  15233. /**
  15234. * Translates the mesh along the passed Vector3 in its local space.
  15235. * Returns the AbstractMesh.
  15236. */
  15237. TransformNode.prototype.locallyTranslate = function (vector3) {
  15238. this.computeWorldMatrix(true);
  15239. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15240. return this;
  15241. };
  15242. /**
  15243. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15244. * @param targetPoint the position (must be in same space as current mesh) to look at
  15245. * @param yawCor optional yaw (y-axis) correction in radians
  15246. * @param pitchCor optional pitch (x-axis) correction in radians
  15247. * @param rollCor optional roll (z-axis) correction in radians
  15248. * @param space the choosen space of the target
  15249. * @returns the TransformNode.
  15250. */
  15251. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15252. if (yawCor === void 0) { yawCor = 0; }
  15253. if (pitchCor === void 0) { pitchCor = 0; }
  15254. if (rollCor === void 0) { rollCor = 0; }
  15255. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15256. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15257. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15258. targetPoint.subtractToRef(pos, dv);
  15259. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15260. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15261. var pitch = Math.atan2(dv.y, len);
  15262. if (this.rotationQuaternion) {
  15263. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15264. }
  15265. else {
  15266. this.rotation.x = pitch + pitchCor;
  15267. this.rotation.y = yaw + yawCor;
  15268. this.rotation.z = rollCor;
  15269. }
  15270. return this;
  15271. };
  15272. /**
  15273. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15274. * This Vector3 is expressed in the World space.
  15275. */
  15276. TransformNode.prototype.getDirection = function (localAxis) {
  15277. var result = BABYLON.Vector3.Zero();
  15278. this.getDirectionToRef(localAxis, result);
  15279. return result;
  15280. };
  15281. /**
  15282. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15283. * localAxis is expressed in the mesh local space.
  15284. * result is computed in the Wordl space from the mesh World matrix.
  15285. * Returns the AbstractMesh.
  15286. */
  15287. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15288. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15289. return this;
  15290. };
  15291. TransformNode.prototype.setPivotPoint = function (point, space) {
  15292. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15293. if (this.getScene().getRenderId() == 0) {
  15294. this.computeWorldMatrix(true);
  15295. }
  15296. var wm = this.getWorldMatrix();
  15297. if (space == BABYLON.Space.WORLD) {
  15298. var tmat = BABYLON.Tmp.Matrix[0];
  15299. wm.invertToRef(tmat);
  15300. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15301. }
  15302. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  15303. this._pivotMatrix.m[12] = -point.x;
  15304. this._pivotMatrix.m[13] = -point.y;
  15305. this._pivotMatrix.m[14] = -point.z;
  15306. this._cache.pivotMatrixUpdated = true;
  15307. return this;
  15308. };
  15309. /**
  15310. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15311. */
  15312. TransformNode.prototype.getPivotPoint = function () {
  15313. var point = BABYLON.Vector3.Zero();
  15314. this.getPivotPointToRef(point);
  15315. return point;
  15316. };
  15317. /**
  15318. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15319. * Returns the AbstractMesh.
  15320. */
  15321. TransformNode.prototype.getPivotPointToRef = function (result) {
  15322. result.x = -this._pivotMatrix.m[12];
  15323. result.y = -this._pivotMatrix.m[13];
  15324. result.z = -this._pivotMatrix.m[14];
  15325. return this;
  15326. };
  15327. /**
  15328. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15329. */
  15330. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15331. var point = BABYLON.Vector3.Zero();
  15332. this.getAbsolutePivotPointToRef(point);
  15333. return point;
  15334. };
  15335. /**
  15336. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15337. * Returns the AbstractMesh.
  15338. */
  15339. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15340. result.x = this._pivotMatrix.m[12];
  15341. result.y = this._pivotMatrix.m[13];
  15342. result.z = this._pivotMatrix.m[14];
  15343. this.getPivotPointToRef(result);
  15344. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15345. return this;
  15346. };
  15347. /**
  15348. * Defines the passed node as the parent of the current node.
  15349. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15350. * Returns the TransformNode.
  15351. */
  15352. TransformNode.prototype.setParent = function (node) {
  15353. if (node === null) {
  15354. var rotation = BABYLON.Tmp.Quaternion[0];
  15355. var position = BABYLON.Tmp.Vector3[0];
  15356. var scale = BABYLON.Tmp.Vector3[1];
  15357. if (this.parent && this.parent.computeWorldMatrix) {
  15358. this.parent.computeWorldMatrix(true);
  15359. }
  15360. this.computeWorldMatrix(true);
  15361. this.getWorldMatrix().decompose(scale, rotation, position);
  15362. if (this.rotationQuaternion) {
  15363. this.rotationQuaternion.copyFrom(rotation);
  15364. }
  15365. else {
  15366. rotation.toEulerAnglesToRef(this.rotation);
  15367. }
  15368. this.scaling.x = scale.x;
  15369. this.scaling.y = scale.y;
  15370. this.scaling.z = scale.z;
  15371. this.position.x = position.x;
  15372. this.position.y = position.y;
  15373. this.position.z = position.z;
  15374. }
  15375. else {
  15376. var rotation = BABYLON.Tmp.Quaternion[0];
  15377. var position = BABYLON.Tmp.Vector3[0];
  15378. var scale = BABYLON.Tmp.Vector3[1];
  15379. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15380. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15381. this.computeWorldMatrix(true);
  15382. node.computeWorldMatrix(true);
  15383. node.getWorldMatrix().invertToRef(invParentMatrix);
  15384. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15385. diffMatrix.decompose(scale, rotation, position);
  15386. if (this.rotationQuaternion) {
  15387. this.rotationQuaternion.copyFrom(rotation);
  15388. }
  15389. else {
  15390. rotation.toEulerAnglesToRef(this.rotation);
  15391. }
  15392. this.position.x = position.x;
  15393. this.position.y = position.y;
  15394. this.position.z = position.z;
  15395. this.scaling.x = scale.x;
  15396. this.scaling.y = scale.y;
  15397. this.scaling.z = scale.z;
  15398. }
  15399. this.parent = node;
  15400. return this;
  15401. };
  15402. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15403. get: function () {
  15404. return this._nonUniformScaling;
  15405. },
  15406. enumerable: true,
  15407. configurable: true
  15408. });
  15409. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15410. if (this._nonUniformScaling === value) {
  15411. return false;
  15412. }
  15413. this._nonUniformScaling = true;
  15414. return true;
  15415. };
  15416. /**
  15417. * Attach the current TransformNode to another TransformNode associated with a bone
  15418. * @param bone Bone affecting the TransformNode
  15419. * @param affectedTransformNode TransformNode associated with the bone
  15420. */
  15421. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15422. this._transformToBoneReferal = affectedTransformNode;
  15423. this.parent = bone;
  15424. if (bone.getWorldMatrix().determinant() < 0) {
  15425. this.scalingDeterminant *= -1;
  15426. }
  15427. return this;
  15428. };
  15429. TransformNode.prototype.detachFromBone = function () {
  15430. if (!this.parent) {
  15431. return this;
  15432. }
  15433. if (this.parent.getWorldMatrix().determinant() < 0) {
  15434. this.scalingDeterminant *= -1;
  15435. }
  15436. this._transformToBoneReferal = null;
  15437. this.parent = null;
  15438. return this;
  15439. };
  15440. /**
  15441. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15442. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15443. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15444. * The passed axis is also normalized.
  15445. * Returns the AbstractMesh.
  15446. */
  15447. TransformNode.prototype.rotate = function (axis, amount, space) {
  15448. axis.normalize();
  15449. if (!this.rotationQuaternion) {
  15450. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15451. this.rotation = BABYLON.Vector3.Zero();
  15452. }
  15453. var rotationQuaternion;
  15454. if (!space || space === BABYLON.Space.LOCAL) {
  15455. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15456. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15457. }
  15458. else {
  15459. if (this.parent) {
  15460. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15461. invertParentWorldMatrix.invert();
  15462. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15463. }
  15464. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15465. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15466. }
  15467. return this;
  15468. };
  15469. /**
  15470. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15471. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15472. * The passed axis is also normalized.
  15473. * Returns the AbstractMesh.
  15474. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15475. */
  15476. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15477. axis.normalize();
  15478. if (!this.rotationQuaternion) {
  15479. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15480. this.rotation.copyFromFloats(0, 0, 0);
  15481. }
  15482. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15483. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15484. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15485. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15486. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15487. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15488. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15489. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15490. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15491. return this;
  15492. };
  15493. /**
  15494. * Translates the mesh along the axis vector for the passed distance in the given space.
  15495. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15496. * Returns the AbstractMesh.
  15497. */
  15498. TransformNode.prototype.translate = function (axis, distance, space) {
  15499. var displacementVector = axis.scale(distance);
  15500. if (!space || space === BABYLON.Space.LOCAL) {
  15501. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15502. this.setPositionWithLocalVector(tempV3);
  15503. }
  15504. else {
  15505. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15506. }
  15507. return this;
  15508. };
  15509. /**
  15510. * Adds a rotation step to the mesh current rotation.
  15511. * x, y, z are Euler angles expressed in radians.
  15512. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15513. * This means this rotation is made in the mesh local space only.
  15514. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15515. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15516. * ```javascript
  15517. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15518. * ```
  15519. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15520. * 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.
  15521. * Returns the AbstractMesh.
  15522. */
  15523. TransformNode.prototype.addRotation = function (x, y, z) {
  15524. var rotationQuaternion;
  15525. if (this.rotationQuaternion) {
  15526. rotationQuaternion = this.rotationQuaternion;
  15527. }
  15528. else {
  15529. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15530. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15531. }
  15532. var accumulation = BABYLON.Tmp.Quaternion[0];
  15533. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15534. rotationQuaternion.multiplyInPlace(accumulation);
  15535. if (!this.rotationQuaternion) {
  15536. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15537. }
  15538. return this;
  15539. };
  15540. /**
  15541. * Computes the mesh World matrix and returns it.
  15542. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15543. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15544. * If the parameter `force`is set to `true`, the actual computation is done.
  15545. * Returns the mesh World Matrix.
  15546. */
  15547. TransformNode.prototype.computeWorldMatrix = function (force) {
  15548. if (this._isWorldMatrixFrozen) {
  15549. return this._worldMatrix;
  15550. }
  15551. if (!force && this.isSynchronized(true)) {
  15552. return this._worldMatrix;
  15553. }
  15554. this._cache.position.copyFrom(this.position);
  15555. this._cache.scaling.copyFrom(this.scaling);
  15556. this._cache.pivotMatrixUpdated = false;
  15557. this._cache.billboardMode = this.billboardMode;
  15558. this._currentRenderId = this.getScene().getRenderId();
  15559. this._isDirty = false;
  15560. // Scaling
  15561. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15562. // Rotation
  15563. //rotate, if quaternion is set and rotation was used
  15564. if (this.rotationQuaternion) {
  15565. var len = this.rotation.length();
  15566. if (len) {
  15567. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15568. this.rotation.copyFromFloats(0, 0, 0);
  15569. }
  15570. }
  15571. if (this.rotationQuaternion) {
  15572. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15573. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15574. }
  15575. else {
  15576. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15577. this._cache.rotation.copyFrom(this.rotation);
  15578. }
  15579. // Translation
  15580. var camera = this.getScene().activeCamera;
  15581. if (this.infiniteDistance && !this.parent && camera) {
  15582. var cameraWorldMatrix = camera.getWorldMatrix();
  15583. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15584. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15585. }
  15586. else {
  15587. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15588. }
  15589. // Composing transformations
  15590. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15591. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15592. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15593. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15594. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15595. // Need to decompose each rotation here
  15596. var currentPosition = BABYLON.Tmp.Vector3[3];
  15597. if (this.parent && this.parent.getWorldMatrix) {
  15598. if (this._transformToBoneReferal) {
  15599. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15600. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15601. }
  15602. else {
  15603. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15604. }
  15605. }
  15606. else {
  15607. currentPosition.copyFrom(this.position);
  15608. }
  15609. currentPosition.subtractInPlace(camera.globalPosition);
  15610. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15611. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15612. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15613. }
  15614. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15615. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15616. }
  15617. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15618. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15619. }
  15620. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15621. }
  15622. else {
  15623. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15624. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15625. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15626. }
  15627. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15628. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15629. }
  15630. // Local world
  15631. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15632. // Parent
  15633. if (this.parent && this.parent.getWorldMatrix) {
  15634. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15635. if (this._transformToBoneReferal) {
  15636. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15637. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15638. }
  15639. else {
  15640. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15641. }
  15642. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15643. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15644. this._worldMatrix.copyFrom(this._localWorld);
  15645. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15646. }
  15647. else {
  15648. if (this._transformToBoneReferal) {
  15649. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15650. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15651. }
  15652. else {
  15653. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15654. }
  15655. }
  15656. this._markSyncedWithParent();
  15657. }
  15658. else {
  15659. this._worldMatrix.copyFrom(this._localWorld);
  15660. }
  15661. // Post multiply inverse of pivotMatrix
  15662. if (this._postMultiplyPivotMatrix) {
  15663. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15664. }
  15665. // Normal matrix
  15666. if (this.scaling.isNonUniform) {
  15667. this._updateNonUniformScalingState(true);
  15668. }
  15669. else if (this.parent && this.parent._nonUniformScaling) {
  15670. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15671. }
  15672. else {
  15673. this._updateNonUniformScalingState(false);
  15674. }
  15675. this._afterComputeWorldMatrix();
  15676. // Absolute position
  15677. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15678. // Callbacks
  15679. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15680. if (!this._poseMatrix) {
  15681. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15682. }
  15683. // Cache the determinant
  15684. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15685. return this._worldMatrix;
  15686. };
  15687. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15688. };
  15689. /**
  15690. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15691. * @param func: callback function to add
  15692. *
  15693. * Returns the TransformNode.
  15694. */
  15695. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15696. this.onAfterWorldMatrixUpdateObservable.add(func);
  15697. return this;
  15698. };
  15699. /**
  15700. * Removes a registered callback function.
  15701. * Returns the TransformNode.
  15702. */
  15703. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15704. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15705. return this;
  15706. };
  15707. /**
  15708. * Clone the current transform node
  15709. * Returns the new transform node
  15710. * @param name Name of the new clone
  15711. * @param newParent New parent for the clone
  15712. * @param doNotCloneChildren Do not clone children hierarchy
  15713. */
  15714. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15715. var _this = this;
  15716. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15717. result.name = name;
  15718. result.id = name;
  15719. if (newParent) {
  15720. result.parent = newParent;
  15721. }
  15722. if (!doNotCloneChildren) {
  15723. // Children
  15724. var directDescendants = this.getDescendants(true);
  15725. for (var index = 0; index < directDescendants.length; index++) {
  15726. var child = directDescendants[index];
  15727. if (child.clone) {
  15728. child.clone(name + "." + child.name, result);
  15729. }
  15730. }
  15731. }
  15732. return result;
  15733. };
  15734. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15735. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15736. serializationObject.type = this.getClassName();
  15737. // Parent
  15738. if (this.parent) {
  15739. serializationObject.parentId = this.parent.id;
  15740. }
  15741. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15742. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15743. }
  15744. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15745. serializationObject.isEnabled = this.isEnabled();
  15746. // Parent
  15747. if (this.parent) {
  15748. serializationObject.parentId = this.parent.id;
  15749. }
  15750. return serializationObject;
  15751. };
  15752. // Statics
  15753. /**
  15754. * Returns a new TransformNode object parsed from the source provided.
  15755. * The parameter `parsedMesh` is the source.
  15756. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15757. */
  15758. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15759. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15760. if (BABYLON.Tags) {
  15761. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15762. }
  15763. if (parsedTransformNode.localMatrix) {
  15764. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15765. }
  15766. else if (parsedTransformNode.pivotMatrix) {
  15767. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15768. }
  15769. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15770. // Parent
  15771. if (parsedTransformNode.parentId) {
  15772. transformNode._waitingParentId = parsedTransformNode.parentId;
  15773. }
  15774. return transformNode;
  15775. };
  15776. /**
  15777. * Disposes the TransformNode.
  15778. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15779. * Returns nothing.
  15780. */
  15781. TransformNode.prototype.dispose = function (doNotRecurse) {
  15782. // Animations
  15783. this.getScene().stopAnimation(this);
  15784. // Remove from scene
  15785. this.getScene().removeTransformNode(this);
  15786. if (!doNotRecurse) {
  15787. // Children
  15788. var objects = this.getDescendants(true);
  15789. for (var index = 0; index < objects.length; index++) {
  15790. objects[index].dispose();
  15791. }
  15792. }
  15793. else {
  15794. var childMeshes = this.getChildMeshes(true);
  15795. for (index = 0; index < childMeshes.length; index++) {
  15796. var child = childMeshes[index];
  15797. child.parent = null;
  15798. child.computeWorldMatrix(true);
  15799. }
  15800. }
  15801. this.onAfterWorldMatrixUpdateObservable.clear();
  15802. _super.prototype.dispose.call(this);
  15803. };
  15804. // Statics
  15805. TransformNode.BILLBOARDMODE_NONE = 0;
  15806. TransformNode.BILLBOARDMODE_X = 1;
  15807. TransformNode.BILLBOARDMODE_Y = 2;
  15808. TransformNode.BILLBOARDMODE_Z = 4;
  15809. TransformNode.BILLBOARDMODE_ALL = 7;
  15810. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15811. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15812. __decorate([
  15813. BABYLON.serializeAsVector3()
  15814. ], TransformNode.prototype, "_rotation", void 0);
  15815. __decorate([
  15816. BABYLON.serializeAsQuaternion()
  15817. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15818. __decorate([
  15819. BABYLON.serializeAsVector3()
  15820. ], TransformNode.prototype, "_scaling", void 0);
  15821. __decorate([
  15822. BABYLON.serialize()
  15823. ], TransformNode.prototype, "billboardMode", void 0);
  15824. __decorate([
  15825. BABYLON.serialize()
  15826. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15827. __decorate([
  15828. BABYLON.serialize()
  15829. ], TransformNode.prototype, "infiniteDistance", void 0);
  15830. __decorate([
  15831. BABYLON.serializeAsVector3()
  15832. ], TransformNode.prototype, "position", void 0);
  15833. return TransformNode;
  15834. }(BABYLON.Node));
  15835. BABYLON.TransformNode = TransformNode;
  15836. })(BABYLON || (BABYLON = {}));
  15837. //# sourceMappingURL=babylon.transformNode.js.map
  15838. var BABYLON;
  15839. (function (BABYLON) {
  15840. var AbstractMesh = /** @class */ (function (_super) {
  15841. __extends(AbstractMesh, _super);
  15842. // Constructor
  15843. function AbstractMesh(name, scene) {
  15844. if (scene === void 0) { scene = null; }
  15845. var _this = _super.call(this, name, scene, false) || this;
  15846. _this._facetNb = 0; // facet number
  15847. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15848. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15849. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15850. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15851. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15852. _this._subDiv = {
  15853. max: 1,
  15854. X: 1,
  15855. Y: 1,
  15856. Z: 1
  15857. };
  15858. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15859. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15860. // Events
  15861. /**
  15862. * An event triggered when this mesh collides with another one
  15863. * @type {BABYLON.Observable}
  15864. */
  15865. _this.onCollideObservable = new BABYLON.Observable();
  15866. /**
  15867. * An event triggered when the collision's position changes
  15868. * @type {BABYLON.Observable}
  15869. */
  15870. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15871. /**
  15872. * An event triggered when material is changed
  15873. * @type {BABYLON.Observable}
  15874. */
  15875. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15876. // Properties
  15877. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15878. /**
  15879. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15880. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15881. * or
  15882. * 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.
  15883. * for more info check WebGl documentations
  15884. */
  15885. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15886. /**
  15887. * 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:
  15888. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15889. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15890. * 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.
  15891. */
  15892. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15893. /**
  15894. * 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.
  15895. * The default value is -1 which means don't break the query and wait till the result.
  15896. */
  15897. _this.occlusionRetryCount = -1;
  15898. _this._occlusionInternalRetryCounter = 0;
  15899. _this._isOccluded = false;
  15900. _this._isOcclusionQueryInProgress = false;
  15901. _this._visibility = 1.0;
  15902. _this.alphaIndex = Number.MAX_VALUE;
  15903. _this.isVisible = true;
  15904. _this.isPickable = true;
  15905. _this.showBoundingBox = false;
  15906. _this.showSubMeshesBoundingBox = false;
  15907. _this.isBlocker = false;
  15908. _this.enablePointerMoveEvents = false;
  15909. _this.renderingGroupId = 0;
  15910. _this._receiveShadows = false;
  15911. _this.renderOutline = false;
  15912. _this.outlineColor = BABYLON.Color3.Red();
  15913. _this.outlineWidth = 0.02;
  15914. _this.renderOverlay = false;
  15915. _this.overlayColor = BABYLON.Color3.Red();
  15916. _this.overlayAlpha = 0.5;
  15917. _this._hasVertexAlpha = false;
  15918. _this._useVertexColors = true;
  15919. _this._computeBonesUsingShaders = true;
  15920. _this._numBoneInfluencers = 4;
  15921. _this._applyFog = true;
  15922. _this.useOctreeForRenderingSelection = true;
  15923. _this.useOctreeForPicking = true;
  15924. _this.useOctreeForCollisions = true;
  15925. _this._layerMask = 0x0FFFFFFF;
  15926. /**
  15927. * True if the mesh must be rendered in any case.
  15928. */
  15929. _this.alwaysSelectAsActiveMesh = false;
  15930. /**
  15931. * This scene's action manager
  15932. * @type {BABYLON.ActionManager}
  15933. */
  15934. _this.actionManager = null;
  15935. // Physics
  15936. _this.physicsImpostor = null;
  15937. // Collisions
  15938. _this._checkCollisions = false;
  15939. _this._collisionMask = -1;
  15940. _this._collisionGroup = -1;
  15941. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15942. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15943. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15944. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15945. // Edges
  15946. _this.edgesWidth = 1;
  15947. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15948. // Cache
  15949. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15950. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15951. _this._isDisposed = false;
  15952. _this._renderId = 0;
  15953. _this._intersectionsInProgress = new Array();
  15954. _this._unIndexed = false;
  15955. _this._lightSources = new Array();
  15956. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15957. if (collidedMesh === void 0) { collidedMesh = null; }
  15958. //TODO move this to the collision coordinator!
  15959. if (_this.getScene().workerCollisions)
  15960. newPosition.multiplyInPlace(_this._collider._radius);
  15961. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15962. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15963. _this.position.addInPlace(_this._diffPositionForCollisions);
  15964. }
  15965. if (collidedMesh) {
  15966. _this.onCollideObservable.notifyObservers(collidedMesh);
  15967. }
  15968. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15969. };
  15970. _this.getScene().addMesh(_this);
  15971. _this._resyncLightSources();
  15972. return _this;
  15973. }
  15974. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15975. get: function () {
  15976. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15977. },
  15978. enumerable: true,
  15979. configurable: true
  15980. });
  15981. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15982. get: function () {
  15983. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15984. },
  15985. enumerable: true,
  15986. configurable: true
  15987. });
  15988. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15989. get: function () {
  15990. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15991. },
  15992. enumerable: true,
  15993. configurable: true
  15994. });
  15995. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15996. get: function () {
  15997. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15998. },
  15999. enumerable: true,
  16000. configurable: true
  16001. });
  16002. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16003. get: function () {
  16004. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16005. },
  16006. enumerable: true,
  16007. configurable: true
  16008. });
  16009. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16010. /**
  16011. * Read-only : the number of facets in the mesh
  16012. */
  16013. get: function () {
  16014. return this._facetNb;
  16015. },
  16016. enumerable: true,
  16017. configurable: true
  16018. });
  16019. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16020. /**
  16021. * The number (integer) of subdivisions per axis in the partioning space
  16022. */
  16023. get: function () {
  16024. return this._partitioningSubdivisions;
  16025. },
  16026. set: function (nb) {
  16027. this._partitioningSubdivisions = nb;
  16028. },
  16029. enumerable: true,
  16030. configurable: true
  16031. });
  16032. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16033. /**
  16034. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16035. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16036. */
  16037. get: function () {
  16038. return this._partitioningBBoxRatio;
  16039. },
  16040. set: function (ratio) {
  16041. this._partitioningBBoxRatio = ratio;
  16042. },
  16043. enumerable: true,
  16044. configurable: true
  16045. });
  16046. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16047. /**
  16048. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16049. * Works only for updatable meshes.
  16050. * Doesn't work with multi-materials.
  16051. */
  16052. get: function () {
  16053. return this._facetDepthSort;
  16054. },
  16055. set: function (sort) {
  16056. this._facetDepthSort = sort;
  16057. },
  16058. enumerable: true,
  16059. configurable: true
  16060. });
  16061. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16062. /**
  16063. * The location (Vector3) where the facet depth sort must be computed from.
  16064. * By default, the active camera position.
  16065. * Used only when facet depth sort is enabled.
  16066. */
  16067. get: function () {
  16068. return this._facetDepthSortFrom;
  16069. },
  16070. set: function (location) {
  16071. this._facetDepthSortFrom = location;
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16077. /**
  16078. * Read-only boolean : is the feature facetData enabled ?
  16079. */
  16080. get: function () {
  16081. return this._facetDataEnabled;
  16082. },
  16083. enumerable: true,
  16084. configurable: true
  16085. });
  16086. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16087. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16088. return false;
  16089. }
  16090. this._markSubMeshesAsMiscDirty();
  16091. return true;
  16092. };
  16093. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16094. set: function (callback) {
  16095. if (this._onCollideObserver) {
  16096. this.onCollideObservable.remove(this._onCollideObserver);
  16097. }
  16098. this._onCollideObserver = this.onCollideObservable.add(callback);
  16099. },
  16100. enumerable: true,
  16101. configurable: true
  16102. });
  16103. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16104. set: function (callback) {
  16105. if (this._onCollisionPositionChangeObserver) {
  16106. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16107. }
  16108. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16109. },
  16110. enumerable: true,
  16111. configurable: true
  16112. });
  16113. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16114. /**
  16115. * 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.
  16116. */
  16117. get: function () {
  16118. return this._isOccluded;
  16119. },
  16120. set: function (value) {
  16121. this._isOccluded = value;
  16122. },
  16123. enumerable: true,
  16124. configurable: true
  16125. });
  16126. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16127. /**
  16128. * Flag to check the progress status of the query
  16129. */
  16130. get: function () {
  16131. return this._isOcclusionQueryInProgress;
  16132. },
  16133. enumerable: true,
  16134. configurable: true
  16135. });
  16136. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16137. /**
  16138. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16139. */
  16140. get: function () {
  16141. return this._visibility;
  16142. },
  16143. /**
  16144. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16145. */
  16146. set: function (value) {
  16147. if (this._visibility === value) {
  16148. return;
  16149. }
  16150. this._visibility = value;
  16151. this._markSubMeshesAsMiscDirty();
  16152. },
  16153. enumerable: true,
  16154. configurable: true
  16155. });
  16156. Object.defineProperty(AbstractMesh.prototype, "material", {
  16157. get: function () {
  16158. return this._material;
  16159. },
  16160. set: function (value) {
  16161. if (this._material === value) {
  16162. return;
  16163. }
  16164. this._material = value;
  16165. if (this.onMaterialChangedObservable.hasObservers) {
  16166. this.onMaterialChangedObservable.notifyObservers(this);
  16167. }
  16168. if (!this.subMeshes) {
  16169. return;
  16170. }
  16171. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16172. var subMesh = _a[_i];
  16173. subMesh.setEffect(null);
  16174. }
  16175. },
  16176. enumerable: true,
  16177. configurable: true
  16178. });
  16179. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16180. get: function () {
  16181. return this._receiveShadows;
  16182. },
  16183. set: function (value) {
  16184. if (this._receiveShadows === value) {
  16185. return;
  16186. }
  16187. this._receiveShadows = value;
  16188. this._markSubMeshesAsLightDirty();
  16189. },
  16190. enumerable: true,
  16191. configurable: true
  16192. });
  16193. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16194. get: function () {
  16195. return this._hasVertexAlpha;
  16196. },
  16197. set: function (value) {
  16198. if (this._hasVertexAlpha === value) {
  16199. return;
  16200. }
  16201. this._hasVertexAlpha = value;
  16202. this._markSubMeshesAsAttributesDirty();
  16203. this._markSubMeshesAsMiscDirty();
  16204. },
  16205. enumerable: true,
  16206. configurable: true
  16207. });
  16208. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16209. get: function () {
  16210. return this._useVertexColors;
  16211. },
  16212. set: function (value) {
  16213. if (this._useVertexColors === value) {
  16214. return;
  16215. }
  16216. this._useVertexColors = value;
  16217. this._markSubMeshesAsAttributesDirty();
  16218. },
  16219. enumerable: true,
  16220. configurable: true
  16221. });
  16222. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16223. get: function () {
  16224. return this._computeBonesUsingShaders;
  16225. },
  16226. set: function (value) {
  16227. if (this._computeBonesUsingShaders === value) {
  16228. return;
  16229. }
  16230. this._computeBonesUsingShaders = value;
  16231. this._markSubMeshesAsAttributesDirty();
  16232. },
  16233. enumerable: true,
  16234. configurable: true
  16235. });
  16236. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16237. get: function () {
  16238. return this._numBoneInfluencers;
  16239. },
  16240. set: function (value) {
  16241. if (this._numBoneInfluencers === value) {
  16242. return;
  16243. }
  16244. this._numBoneInfluencers = value;
  16245. this._markSubMeshesAsAttributesDirty();
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16251. get: function () {
  16252. return this._applyFog;
  16253. },
  16254. set: function (value) {
  16255. if (this._applyFog === value) {
  16256. return;
  16257. }
  16258. this._applyFog = value;
  16259. this._markSubMeshesAsMiscDirty();
  16260. },
  16261. enumerable: true,
  16262. configurable: true
  16263. });
  16264. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16265. get: function () {
  16266. return this._layerMask;
  16267. },
  16268. set: function (value) {
  16269. if (value === this._layerMask) {
  16270. return;
  16271. }
  16272. this._layerMask = value;
  16273. this._resyncLightSources();
  16274. },
  16275. enumerable: true,
  16276. configurable: true
  16277. });
  16278. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16279. get: function () {
  16280. return this._collisionMask;
  16281. },
  16282. set: function (mask) {
  16283. this._collisionMask = !isNaN(mask) ? mask : -1;
  16284. },
  16285. enumerable: true,
  16286. configurable: true
  16287. });
  16288. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16289. get: function () {
  16290. return this._collisionGroup;
  16291. },
  16292. set: function (mask) {
  16293. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16299. get: function () {
  16300. return null;
  16301. },
  16302. enumerable: true,
  16303. configurable: true
  16304. });
  16305. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16306. get: function () {
  16307. return this._skeleton;
  16308. },
  16309. set: function (value) {
  16310. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16311. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16312. }
  16313. if (value && value.needInitialSkinMatrix) {
  16314. value._registerMeshWithPoseMatrix(this);
  16315. }
  16316. this._skeleton = value;
  16317. if (!this._skeleton) {
  16318. this._bonesTransformMatrices = null;
  16319. }
  16320. this._markSubMeshesAsAttributesDirty();
  16321. },
  16322. enumerable: true,
  16323. configurable: true
  16324. });
  16325. /**
  16326. * Boolean : true if the mesh has been disposed.
  16327. */
  16328. AbstractMesh.prototype.isDisposed = function () {
  16329. return this._isDisposed;
  16330. };
  16331. /**
  16332. * Returns the string "AbstractMesh"
  16333. */
  16334. AbstractMesh.prototype.getClassName = function () {
  16335. return "AbstractMesh";
  16336. };
  16337. /**
  16338. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16339. */
  16340. AbstractMesh.prototype.toString = function (fullDetails) {
  16341. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16342. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16343. if (this._skeleton) {
  16344. ret += ", skeleton: " + this._skeleton.name;
  16345. }
  16346. if (fullDetails) {
  16347. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16348. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16349. }
  16350. return ret;
  16351. };
  16352. AbstractMesh.prototype._rebuild = function () {
  16353. if (this._occlusionQuery) {
  16354. this._occlusionQuery = null;
  16355. }
  16356. if (this._edgesRenderer) {
  16357. this._edgesRenderer._rebuild();
  16358. }
  16359. if (!this.subMeshes) {
  16360. return;
  16361. }
  16362. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16363. var subMesh = _a[_i];
  16364. subMesh._rebuild();
  16365. }
  16366. };
  16367. AbstractMesh.prototype._resyncLightSources = function () {
  16368. this._lightSources.length = 0;
  16369. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16370. var light = _a[_i];
  16371. if (!light.isEnabled()) {
  16372. continue;
  16373. }
  16374. if (light.canAffectMesh(this)) {
  16375. this._lightSources.push(light);
  16376. }
  16377. }
  16378. this._markSubMeshesAsLightDirty();
  16379. };
  16380. AbstractMesh.prototype._resyncLighSource = function (light) {
  16381. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16382. var index = this._lightSources.indexOf(light);
  16383. if (index === -1) {
  16384. if (!isIn) {
  16385. return;
  16386. }
  16387. this._lightSources.push(light);
  16388. }
  16389. else {
  16390. if (isIn) {
  16391. return;
  16392. }
  16393. this._lightSources.splice(index, 1);
  16394. }
  16395. this._markSubMeshesAsLightDirty();
  16396. };
  16397. AbstractMesh.prototype._removeLightSource = function (light) {
  16398. var index = this._lightSources.indexOf(light);
  16399. if (index === -1) {
  16400. return;
  16401. }
  16402. this._lightSources.splice(index, 1);
  16403. this._markSubMeshesAsLightDirty();
  16404. };
  16405. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16406. if (!this.subMeshes) {
  16407. return;
  16408. }
  16409. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16410. var subMesh = _a[_i];
  16411. if (subMesh._materialDefines) {
  16412. func(subMesh._materialDefines);
  16413. }
  16414. }
  16415. };
  16416. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16417. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16418. };
  16419. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16420. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16421. };
  16422. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16423. if (!this.subMeshes) {
  16424. return;
  16425. }
  16426. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16427. var subMesh = _a[_i];
  16428. var material = subMesh.getMaterial();
  16429. if (material) {
  16430. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16431. }
  16432. }
  16433. };
  16434. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16435. /**
  16436. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16437. * Default : (1.0, 1.0, 1.0)
  16438. */
  16439. get: function () {
  16440. return this._scaling;
  16441. },
  16442. /**
  16443. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16444. * Default : (1.0, 1.0, 1.0)
  16445. */
  16446. set: function (newScaling) {
  16447. this._scaling = newScaling;
  16448. if (this.physicsImpostor) {
  16449. this.physicsImpostor.forceUpdate();
  16450. }
  16451. },
  16452. enumerable: true,
  16453. configurable: true
  16454. });
  16455. // Methods
  16456. /**
  16457. * Disables the mesh edger rendering mode.
  16458. * Returns the AbstractMesh.
  16459. */
  16460. AbstractMesh.prototype.disableEdgesRendering = function () {
  16461. if (this._edgesRenderer) {
  16462. this._edgesRenderer.dispose();
  16463. this._edgesRenderer = null;
  16464. }
  16465. return this;
  16466. };
  16467. /**
  16468. * Enables the edge rendering mode on the mesh.
  16469. * This mode makes the mesh edges visible.
  16470. * Returns the AbstractMesh.
  16471. */
  16472. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16473. if (epsilon === void 0) { epsilon = 0.95; }
  16474. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16475. this.disableEdgesRendering();
  16476. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16477. return this;
  16478. };
  16479. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16480. /**
  16481. * Returns true if the mesh is blocked. Used by the class Mesh.
  16482. * Returns the boolean `false` by default.
  16483. */
  16484. get: function () {
  16485. return false;
  16486. },
  16487. enumerable: true,
  16488. configurable: true
  16489. });
  16490. /**
  16491. * Returns the mesh itself by default, used by the class Mesh.
  16492. * Returned type : AbstractMesh
  16493. */
  16494. AbstractMesh.prototype.getLOD = function (camera) {
  16495. return this;
  16496. };
  16497. /**
  16498. * Returns 0 by default, used by the class Mesh.
  16499. * Returns an integer.
  16500. */
  16501. AbstractMesh.prototype.getTotalVertices = function () {
  16502. return 0;
  16503. };
  16504. /**
  16505. * Returns null by default, used by the class Mesh.
  16506. * Returned type : integer array
  16507. */
  16508. AbstractMesh.prototype.getIndices = function () {
  16509. return null;
  16510. };
  16511. /**
  16512. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16513. * Returned type : float array or Float32Array
  16514. */
  16515. AbstractMesh.prototype.getVerticesData = function (kind) {
  16516. return null;
  16517. };
  16518. /**
  16519. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16520. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16521. * The `data` are either a numeric array either a Float32Array.
  16522. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16523. * 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).
  16524. * Note that a new underlying VertexBuffer object is created each call.
  16525. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16526. *
  16527. * Possible `kind` values :
  16528. * - BABYLON.VertexBuffer.PositionKind
  16529. * - BABYLON.VertexBuffer.UVKind
  16530. * - BABYLON.VertexBuffer.UV2Kind
  16531. * - BABYLON.VertexBuffer.UV3Kind
  16532. * - BABYLON.VertexBuffer.UV4Kind
  16533. * - BABYLON.VertexBuffer.UV5Kind
  16534. * - BABYLON.VertexBuffer.UV6Kind
  16535. * - BABYLON.VertexBuffer.ColorKind
  16536. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16537. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16538. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16539. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16540. *
  16541. * Returns the Mesh.
  16542. */
  16543. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16544. return this;
  16545. };
  16546. /**
  16547. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16548. * If the mesh has no geometry, it is simply returned as it is.
  16549. * The `data` are either a numeric array either a Float32Array.
  16550. * No new underlying VertexBuffer object is created.
  16551. * 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.
  16552. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16553. *
  16554. * Possible `kind` values :
  16555. * - BABYLON.VertexBuffer.PositionKind
  16556. * - BABYLON.VertexBuffer.UVKind
  16557. * - BABYLON.VertexBuffer.UV2Kind
  16558. * - BABYLON.VertexBuffer.UV3Kind
  16559. * - BABYLON.VertexBuffer.UV4Kind
  16560. * - BABYLON.VertexBuffer.UV5Kind
  16561. * - BABYLON.VertexBuffer.UV6Kind
  16562. * - BABYLON.VertexBuffer.ColorKind
  16563. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16564. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16565. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16566. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16567. *
  16568. * Returns the Mesh.
  16569. */
  16570. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16571. return this;
  16572. };
  16573. /**
  16574. * Sets the mesh indices.
  16575. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16576. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16577. * This method creates a new index buffer each call.
  16578. * Returns the Mesh.
  16579. */
  16580. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16581. return this;
  16582. };
  16583. /** Returns false by default, used by the class Mesh.
  16584. * Returns a boolean
  16585. */
  16586. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16587. return false;
  16588. };
  16589. /**
  16590. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16591. * Returns a BoundingInfo
  16592. */
  16593. AbstractMesh.prototype.getBoundingInfo = function () {
  16594. if (this._masterMesh) {
  16595. return this._masterMesh.getBoundingInfo();
  16596. }
  16597. if (!this._boundingInfo) {
  16598. // this._boundingInfo is being created here
  16599. this._updateBoundingInfo();
  16600. }
  16601. // cannot be null.
  16602. return this._boundingInfo;
  16603. };
  16604. /**
  16605. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16606. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16607. */
  16608. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16609. if (includeDescendants === void 0) { includeDescendants = true; }
  16610. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16611. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16612. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16613. if (maxDimension === 0) {
  16614. return this;
  16615. }
  16616. var scale = 1 / maxDimension;
  16617. this.scaling.scaleInPlace(scale);
  16618. return this;
  16619. };
  16620. /**
  16621. * Sets a mesh new object BoundingInfo.
  16622. * Returns the AbstractMesh.
  16623. */
  16624. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16625. this._boundingInfo = boundingInfo;
  16626. return this;
  16627. };
  16628. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16629. get: function () {
  16630. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16631. },
  16632. enumerable: true,
  16633. configurable: true
  16634. });
  16635. AbstractMesh.prototype._preActivate = function () {
  16636. };
  16637. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16638. };
  16639. AbstractMesh.prototype._activate = function (renderId) {
  16640. this._renderId = renderId;
  16641. };
  16642. /**
  16643. * Returns the latest update of the World matrix
  16644. * Returns a Matrix.
  16645. */
  16646. AbstractMesh.prototype.getWorldMatrix = function () {
  16647. if (this._masterMesh) {
  16648. return this._masterMesh.getWorldMatrix();
  16649. }
  16650. return _super.prototype.getWorldMatrix.call(this);
  16651. };
  16652. /**
  16653. * Returns the latest update of the World matrix determinant.
  16654. */
  16655. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16656. if (this._masterMesh) {
  16657. return this._masterMesh._getWorldMatrixDeterminant();
  16658. }
  16659. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16660. };
  16661. // ================================== Point of View Movement =================================
  16662. /**
  16663. * Perform relative position change from the point of view of behind the front of the mesh.
  16664. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16665. * Supports definition of mesh facing forward or backward.
  16666. * @param {number} amountRight
  16667. * @param {number} amountUp
  16668. * @param {number} amountForward
  16669. *
  16670. * Returns the AbstractMesh.
  16671. */
  16672. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16673. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16674. return this;
  16675. };
  16676. /**
  16677. * Calculate relative position change from the point of view of behind the front of the mesh.
  16678. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16679. * Supports definition of mesh facing forward or backward.
  16680. * @param {number} amountRight
  16681. * @param {number} amountUp
  16682. * @param {number} amountForward
  16683. *
  16684. * Returns a new Vector3.
  16685. */
  16686. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16687. var rotMatrix = new BABYLON.Matrix();
  16688. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16689. rotQuaternion.toRotationMatrix(rotMatrix);
  16690. var translationDelta = BABYLON.Vector3.Zero();
  16691. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16692. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16693. return translationDelta;
  16694. };
  16695. // ================================== Point of View Rotation =================================
  16696. /**
  16697. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16698. * Supports definition of mesh facing forward or backward.
  16699. * @param {number} flipBack
  16700. * @param {number} twirlClockwise
  16701. * @param {number} tiltRight
  16702. *
  16703. * Returns the AbstractMesh.
  16704. */
  16705. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16706. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16707. return this;
  16708. };
  16709. /**
  16710. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16711. * Supports definition of mesh facing forward or backward.
  16712. * @param {number} flipBack
  16713. * @param {number} twirlClockwise
  16714. * @param {number} tiltRight
  16715. *
  16716. * Returns a new Vector3.
  16717. */
  16718. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16719. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16720. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16721. };
  16722. /**
  16723. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16724. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16725. */
  16726. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16727. if (includeDescendants === void 0) { includeDescendants = true; }
  16728. this.computeWorldMatrix(true);
  16729. var min;
  16730. var max;
  16731. var boundingInfo = this.getBoundingInfo();
  16732. if (!this.subMeshes) {
  16733. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16734. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16735. }
  16736. else {
  16737. min = boundingInfo.boundingBox.minimumWorld;
  16738. max = boundingInfo.boundingBox.maximumWorld;
  16739. }
  16740. if (includeDescendants) {
  16741. var descendants = this.getDescendants(false);
  16742. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16743. var descendant = descendants_1[_i];
  16744. var childMesh = descendant;
  16745. childMesh.computeWorldMatrix(true);
  16746. //make sure we have the needed params to get mix and max
  16747. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16748. continue;
  16749. }
  16750. var childBoundingInfo = childMesh.getBoundingInfo();
  16751. var boundingBox = childBoundingInfo.boundingBox;
  16752. var minBox = boundingBox.minimumWorld;
  16753. var maxBox = boundingBox.maximumWorld;
  16754. BABYLON.Tools.CheckExtends(minBox, min, max);
  16755. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16756. }
  16757. }
  16758. return {
  16759. min: min,
  16760. max: max
  16761. };
  16762. };
  16763. /**
  16764. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16765. * Returns the AbstractMesh.
  16766. */
  16767. AbstractMesh.prototype._updateBoundingInfo = function () {
  16768. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16769. this._boundingInfo.update(this.worldMatrixFromCache);
  16770. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16771. return this;
  16772. };
  16773. /**
  16774. * Update a mesh's children BoundingInfo objects only.
  16775. * Returns the AbstractMesh.
  16776. */
  16777. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16778. if (!this.subMeshes) {
  16779. return this;
  16780. }
  16781. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16782. var subMesh = this.subMeshes[subIndex];
  16783. if (!subMesh.IsGlobal) {
  16784. subMesh.updateBoundingInfo(matrix);
  16785. }
  16786. }
  16787. return this;
  16788. };
  16789. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16790. // Bounding info
  16791. this._updateBoundingInfo();
  16792. };
  16793. /**
  16794. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16795. * A mesh is in the frustum if its bounding box intersects the frustum.
  16796. * Boolean returned.
  16797. */
  16798. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16799. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16800. };
  16801. /**
  16802. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16803. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16804. * Boolean returned.
  16805. */
  16806. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16807. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16808. ;
  16809. };
  16810. /**
  16811. * True if the mesh intersects another mesh or a SolidParticle object.
  16812. * 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)
  16813. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16814. * Returns a boolean.
  16815. */
  16816. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16817. if (precise === void 0) { precise = false; }
  16818. if (!this._boundingInfo || !mesh._boundingInfo) {
  16819. return false;
  16820. }
  16821. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16822. return true;
  16823. }
  16824. if (includeDescendants) {
  16825. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16826. var child = _a[_i];
  16827. if (child.intersectsMesh(mesh, precise, true)) {
  16828. return true;
  16829. }
  16830. }
  16831. }
  16832. return false;
  16833. };
  16834. /**
  16835. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16836. * Returns a boolean.
  16837. */
  16838. AbstractMesh.prototype.intersectsPoint = function (point) {
  16839. if (!this._boundingInfo) {
  16840. return false;
  16841. }
  16842. return this._boundingInfo.intersectsPoint(point);
  16843. };
  16844. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16845. return this.physicsImpostor;
  16846. };
  16847. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16848. if (camera === void 0) { camera = null; }
  16849. if (!camera) {
  16850. camera = this.getScene().activeCamera;
  16851. }
  16852. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16853. };
  16854. /**
  16855. * Returns the distance from the mesh to the active camera.
  16856. * Returns a float.
  16857. */
  16858. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16859. if (camera === void 0) { camera = null; }
  16860. if (!camera) {
  16861. camera = this.getScene().activeCamera;
  16862. }
  16863. return this.absolutePosition.subtract(camera.position).length();
  16864. };
  16865. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16866. if (!this.physicsImpostor) {
  16867. return this;
  16868. }
  16869. this.physicsImpostor.applyImpulse(force, contactPoint);
  16870. return this;
  16871. };
  16872. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16873. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16874. return this;
  16875. }
  16876. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16877. mainPivot: pivot1,
  16878. connectedPivot: pivot2,
  16879. nativeParams: options
  16880. });
  16881. return this;
  16882. };
  16883. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16884. // Collisions
  16885. /**
  16886. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16887. * Default `false`.
  16888. */
  16889. get: function () {
  16890. return this._checkCollisions;
  16891. },
  16892. set: function (collisionEnabled) {
  16893. this._checkCollisions = collisionEnabled;
  16894. if (this.getScene().workerCollisions) {
  16895. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16896. }
  16897. },
  16898. enumerable: true,
  16899. configurable: true
  16900. });
  16901. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16902. /**
  16903. * Gets Collider object used to compute collisions (not physics)
  16904. */
  16905. get: function () {
  16906. return this._collider;
  16907. },
  16908. enumerable: true,
  16909. configurable: true
  16910. });
  16911. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16912. var globalPosition = this.getAbsolutePosition();
  16913. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16914. if (!this._collider) {
  16915. this._collider = new BABYLON.Collider();
  16916. }
  16917. this._collider._radius = this.ellipsoid;
  16918. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16919. return this;
  16920. };
  16921. // Submeshes octree
  16922. /**
  16923. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16924. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16925. * Returns an Octree of submeshes.
  16926. */
  16927. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16928. if (maxCapacity === void 0) { maxCapacity = 64; }
  16929. if (maxDepth === void 0) { maxDepth = 2; }
  16930. if (!this._submeshesOctree) {
  16931. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16932. }
  16933. this.computeWorldMatrix(true);
  16934. var boundingInfo = this.getBoundingInfo();
  16935. // Update octree
  16936. var bbox = boundingInfo.boundingBox;
  16937. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16938. return this._submeshesOctree;
  16939. };
  16940. // Collisions
  16941. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16942. this._generatePointsArray();
  16943. if (!this._positions) {
  16944. return this;
  16945. }
  16946. // Transformation
  16947. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16948. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16949. subMesh._lastColliderWorldVertices = [];
  16950. subMesh._trianglePlanes = [];
  16951. var start = subMesh.verticesStart;
  16952. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16953. for (var i = start; i < end; i++) {
  16954. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16955. }
  16956. }
  16957. // Collide
  16958. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16959. if (collider.collisionFound) {
  16960. collider.collidedMesh = this;
  16961. }
  16962. return this;
  16963. };
  16964. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16965. var subMeshes;
  16966. var len;
  16967. // Octrees
  16968. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16969. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16970. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16971. len = intersections.length;
  16972. subMeshes = intersections.data;
  16973. }
  16974. else {
  16975. subMeshes = this.subMeshes;
  16976. len = subMeshes.length;
  16977. }
  16978. for (var index = 0; index < len; index++) {
  16979. var subMesh = subMeshes[index];
  16980. // Bounding test
  16981. if (len > 1 && !subMesh._checkCollision(collider))
  16982. continue;
  16983. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16984. }
  16985. return this;
  16986. };
  16987. AbstractMesh.prototype._checkCollision = function (collider) {
  16988. // Bounding box test
  16989. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16990. return this;
  16991. // Transformation matrix
  16992. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16993. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16994. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16995. return this;
  16996. };
  16997. // Picking
  16998. AbstractMesh.prototype._generatePointsArray = function () {
  16999. return false;
  17000. };
  17001. /**
  17002. * Checks if the passed Ray intersects with the mesh.
  17003. * Returns an object PickingInfo.
  17004. */
  17005. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17006. var pickingInfo = new BABYLON.PickingInfo();
  17007. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17008. return pickingInfo;
  17009. }
  17010. if (!this._generatePointsArray()) {
  17011. return pickingInfo;
  17012. }
  17013. var intersectInfo = null;
  17014. // Octrees
  17015. var subMeshes;
  17016. var len;
  17017. if (this._submeshesOctree && this.useOctreeForPicking) {
  17018. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17019. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17020. len = intersections.length;
  17021. subMeshes = intersections.data;
  17022. }
  17023. else {
  17024. subMeshes = this.subMeshes;
  17025. len = subMeshes.length;
  17026. }
  17027. for (var index = 0; index < len; index++) {
  17028. var subMesh = subMeshes[index];
  17029. // Bounding test
  17030. if (len > 1 && !subMesh.canIntersects(ray))
  17031. continue;
  17032. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17033. if (currentIntersectInfo) {
  17034. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17035. intersectInfo = currentIntersectInfo;
  17036. intersectInfo.subMeshId = index;
  17037. if (fastCheck) {
  17038. break;
  17039. }
  17040. }
  17041. }
  17042. }
  17043. if (intersectInfo) {
  17044. // Get picked point
  17045. var world = this.getWorldMatrix();
  17046. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17047. var direction = ray.direction.clone();
  17048. direction = direction.scale(intersectInfo.distance);
  17049. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17050. var pickedPoint = worldOrigin.add(worldDirection);
  17051. // Return result
  17052. pickingInfo.hit = true;
  17053. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17054. pickingInfo.pickedPoint = pickedPoint;
  17055. pickingInfo.pickedMesh = this;
  17056. pickingInfo.bu = intersectInfo.bu || 0;
  17057. pickingInfo.bv = intersectInfo.bv || 0;
  17058. pickingInfo.faceId = intersectInfo.faceId;
  17059. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17060. return pickingInfo;
  17061. }
  17062. return pickingInfo;
  17063. };
  17064. /**
  17065. * Clones the mesh, used by the class Mesh.
  17066. * Just returns `null` for an AbstractMesh.
  17067. */
  17068. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17069. return null;
  17070. };
  17071. /**
  17072. * Disposes all the mesh submeshes.
  17073. * Returns the AbstractMesh.
  17074. */
  17075. AbstractMesh.prototype.releaseSubMeshes = function () {
  17076. if (this.subMeshes) {
  17077. while (this.subMeshes.length) {
  17078. this.subMeshes[0].dispose();
  17079. }
  17080. }
  17081. else {
  17082. this.subMeshes = new Array();
  17083. }
  17084. return this;
  17085. };
  17086. /**
  17087. * Disposes the AbstractMesh.
  17088. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17089. * Returns nothing.
  17090. */
  17091. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17092. var _this = this;
  17093. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17094. var index;
  17095. // Action manager
  17096. if (this.actionManager !== undefined && this.actionManager !== null) {
  17097. this.actionManager.dispose();
  17098. this.actionManager = null;
  17099. }
  17100. // Skeleton
  17101. this.skeleton = null;
  17102. // Physics
  17103. if (this.physicsImpostor) {
  17104. this.physicsImpostor.dispose();
  17105. }
  17106. // Intersections in progress
  17107. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17108. var other = this._intersectionsInProgress[index];
  17109. var pos = other._intersectionsInProgress.indexOf(this);
  17110. other._intersectionsInProgress.splice(pos, 1);
  17111. }
  17112. this._intersectionsInProgress = [];
  17113. // Lights
  17114. var lights = this.getScene().lights;
  17115. lights.forEach(function (light) {
  17116. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17117. if (meshIndex !== -1) {
  17118. light.includedOnlyMeshes.splice(meshIndex, 1);
  17119. }
  17120. meshIndex = light.excludedMeshes.indexOf(_this);
  17121. if (meshIndex !== -1) {
  17122. light.excludedMeshes.splice(meshIndex, 1);
  17123. }
  17124. // Shadow generators
  17125. var generator = light.getShadowGenerator();
  17126. if (generator) {
  17127. var shadowMap = generator.getShadowMap();
  17128. if (shadowMap && shadowMap.renderList) {
  17129. meshIndex = shadowMap.renderList.indexOf(_this);
  17130. if (meshIndex !== -1) {
  17131. shadowMap.renderList.splice(meshIndex, 1);
  17132. }
  17133. }
  17134. }
  17135. });
  17136. // Edges
  17137. if (this._edgesRenderer) {
  17138. this._edgesRenderer.dispose();
  17139. this._edgesRenderer = null;
  17140. }
  17141. // SubMeshes
  17142. if (this.getClassName() !== "InstancedMesh") {
  17143. this.releaseSubMeshes();
  17144. }
  17145. // Octree
  17146. var sceneOctree = this.getScene().selectionOctree;
  17147. if (sceneOctree !== undefined && sceneOctree !== null) {
  17148. var index = sceneOctree.dynamicContent.indexOf(this);
  17149. if (index !== -1) {
  17150. sceneOctree.dynamicContent.splice(index, 1);
  17151. }
  17152. }
  17153. // Query
  17154. var engine = this.getScene().getEngine();
  17155. if (this._occlusionQuery) {
  17156. this._isOcclusionQueryInProgress = false;
  17157. engine.deleteQuery(this._occlusionQuery);
  17158. this._occlusionQuery = null;
  17159. }
  17160. // Engine
  17161. engine.wipeCaches();
  17162. // Remove from scene
  17163. this.getScene().removeMesh(this);
  17164. if (disposeMaterialAndTextures) {
  17165. if (this.material) {
  17166. this.material.dispose(false, true);
  17167. }
  17168. }
  17169. if (!doNotRecurse) {
  17170. // Particles
  17171. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17172. if (this.getScene().particleSystems[index].emitter === this) {
  17173. this.getScene().particleSystems[index].dispose();
  17174. index--;
  17175. }
  17176. }
  17177. }
  17178. // facet data
  17179. if (this._facetDataEnabled) {
  17180. this.disableFacetData();
  17181. }
  17182. this.onAfterWorldMatrixUpdateObservable.clear();
  17183. this.onCollideObservable.clear();
  17184. this.onCollisionPositionChangeObservable.clear();
  17185. this._isDisposed = true;
  17186. _super.prototype.dispose.call(this, doNotRecurse);
  17187. };
  17188. /**
  17189. * Adds the passed mesh as a child to the current mesh.
  17190. * Returns the AbstractMesh.
  17191. */
  17192. AbstractMesh.prototype.addChild = function (mesh) {
  17193. mesh.setParent(this);
  17194. return this;
  17195. };
  17196. /**
  17197. * Removes the passed mesh from the current mesh children list.
  17198. * Returns the AbstractMesh.
  17199. */
  17200. AbstractMesh.prototype.removeChild = function (mesh) {
  17201. mesh.setParent(null);
  17202. return this;
  17203. };
  17204. // Facet data
  17205. /**
  17206. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17207. * Returns the AbstractMesh.
  17208. */
  17209. AbstractMesh.prototype._initFacetData = function () {
  17210. if (!this._facetNormals) {
  17211. this._facetNormals = new Array();
  17212. }
  17213. if (!this._facetPositions) {
  17214. this._facetPositions = new Array();
  17215. }
  17216. if (!this._facetPartitioning) {
  17217. this._facetPartitioning = new Array();
  17218. }
  17219. this._facetNb = (this.getIndices().length / 3) | 0;
  17220. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17221. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17222. for (var f = 0; f < this._facetNb; f++) {
  17223. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17224. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17225. }
  17226. this._facetDataEnabled = true;
  17227. return this;
  17228. };
  17229. /**
  17230. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17231. * This method can be called within the render loop.
  17232. * 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.
  17233. * Returns the AbstractMesh.
  17234. */
  17235. AbstractMesh.prototype.updateFacetData = function () {
  17236. if (!this._facetDataEnabled) {
  17237. this._initFacetData();
  17238. }
  17239. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17240. var indices = this.getIndices();
  17241. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17242. var bInfo = this.getBoundingInfo();
  17243. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17244. // init arrays, matrix and sort function on first call
  17245. this._facetDepthSortEnabled = true;
  17246. if (indices instanceof Uint16Array) {
  17247. this._depthSortedIndices = new Uint16Array(indices);
  17248. }
  17249. else if (indices instanceof Uint32Array) {
  17250. this._depthSortedIndices = new Uint32Array(indices);
  17251. }
  17252. else {
  17253. var needs32bits = false;
  17254. for (var i = 0; i < indices.length; i++) {
  17255. if (indices[i] > 65535) {
  17256. needs32bits = true;
  17257. break;
  17258. }
  17259. }
  17260. if (needs32bits) {
  17261. this._depthSortedIndices = new Uint32Array(indices);
  17262. }
  17263. else {
  17264. this._depthSortedIndices = new Uint16Array(indices);
  17265. }
  17266. }
  17267. this._facetDepthSortFunction = function (f1, f2) {
  17268. return (f2.sqDistance - f1.sqDistance);
  17269. };
  17270. if (!this._facetDepthSortFrom) {
  17271. var camera = this.getScene().activeCamera;
  17272. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17273. }
  17274. this._depthSortedFacets = [];
  17275. for (var f = 0; f < this._facetNb; f++) {
  17276. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17277. this._depthSortedFacets.push(depthSortedFacet);
  17278. }
  17279. this._invertedMatrix = BABYLON.Matrix.Identity();
  17280. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17281. }
  17282. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17283. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17284. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17285. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17286. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17287. this._subDiv.max = this._partitioningSubdivisions;
  17288. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17289. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17290. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17291. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17292. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17293. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17294. // set the parameters for ComputeNormals()
  17295. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17296. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17297. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17298. this._facetParameters.bInfo = bInfo;
  17299. this._facetParameters.bbSize = this._bbSize;
  17300. this._facetParameters.subDiv = this._subDiv;
  17301. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17302. this._facetParameters.depthSort = this._facetDepthSort;
  17303. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17304. this.computeWorldMatrix(true);
  17305. this._worldMatrix.invertToRef(this._invertedMatrix);
  17306. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17307. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17308. }
  17309. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17310. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17311. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17312. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17313. var l = (this._depthSortedIndices.length / 3) | 0;
  17314. for (var f = 0; f < l; f++) {
  17315. var sind = this._depthSortedFacets[f].ind;
  17316. this._depthSortedIndices[f * 3] = indices[sind];
  17317. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17318. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17319. }
  17320. this.updateIndices(this._depthSortedIndices);
  17321. }
  17322. return this;
  17323. };
  17324. /**
  17325. * Returns the facetLocalNormals array.
  17326. * The normals are expressed in the mesh local space.
  17327. */
  17328. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17329. if (!this._facetNormals) {
  17330. this.updateFacetData();
  17331. }
  17332. return this._facetNormals;
  17333. };
  17334. /**
  17335. * Returns the facetLocalPositions array.
  17336. * The facet positions are expressed in the mesh local space.
  17337. */
  17338. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17339. if (!this._facetPositions) {
  17340. this.updateFacetData();
  17341. }
  17342. return this._facetPositions;
  17343. };
  17344. /**
  17345. * Returns the facetLocalPartioning array.
  17346. */
  17347. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17348. if (!this._facetPartitioning) {
  17349. this.updateFacetData();
  17350. }
  17351. return this._facetPartitioning;
  17352. };
  17353. /**
  17354. * Returns the i-th facet position in the world system.
  17355. * This method allocates a new Vector3 per call.
  17356. */
  17357. AbstractMesh.prototype.getFacetPosition = function (i) {
  17358. var pos = BABYLON.Vector3.Zero();
  17359. this.getFacetPositionToRef(i, pos);
  17360. return pos;
  17361. };
  17362. /**
  17363. * Sets the reference Vector3 with the i-th facet position in the world system.
  17364. * Returns the AbstractMesh.
  17365. */
  17366. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17367. var localPos = (this.getFacetLocalPositions())[i];
  17368. var world = this.getWorldMatrix();
  17369. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17370. return this;
  17371. };
  17372. /**
  17373. * Returns the i-th facet normal in the world system.
  17374. * This method allocates a new Vector3 per call.
  17375. */
  17376. AbstractMesh.prototype.getFacetNormal = function (i) {
  17377. var norm = BABYLON.Vector3.Zero();
  17378. this.getFacetNormalToRef(i, norm);
  17379. return norm;
  17380. };
  17381. /**
  17382. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17383. * Returns the AbstractMesh.
  17384. */
  17385. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17386. var localNorm = (this.getFacetLocalNormals())[i];
  17387. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17388. return this;
  17389. };
  17390. /**
  17391. * 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).
  17392. */
  17393. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17394. var bInfo = this.getBoundingInfo();
  17395. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17396. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17397. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17398. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17399. return null;
  17400. }
  17401. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17402. };
  17403. /**
  17404. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17405. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17406. * 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.
  17407. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17408. * 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.
  17409. */
  17410. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17411. if (checkFace === void 0) { checkFace = false; }
  17412. if (facing === void 0) { facing = true; }
  17413. var world = this.getWorldMatrix();
  17414. var invMat = BABYLON.Tmp.Matrix[5];
  17415. world.invertToRef(invMat);
  17416. var invVect = BABYLON.Tmp.Vector3[8];
  17417. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17418. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17419. if (projected) {
  17420. // tranform the local computed projected vector to world coordinates
  17421. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17422. }
  17423. return closest;
  17424. };
  17425. /**
  17426. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17427. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17428. * 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.
  17429. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17430. * 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.
  17431. */
  17432. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17433. if (checkFace === void 0) { checkFace = false; }
  17434. if (facing === void 0) { facing = true; }
  17435. var closest = null;
  17436. var tmpx = 0.0;
  17437. var tmpy = 0.0;
  17438. var tmpz = 0.0;
  17439. var d = 0.0; // tmp dot facet normal * facet position
  17440. var t0 = 0.0;
  17441. var projx = 0.0;
  17442. var projy = 0.0;
  17443. var projz = 0.0;
  17444. // Get all the facets in the same partitioning block than (x, y, z)
  17445. var facetPositions = this.getFacetLocalPositions();
  17446. var facetNormals = this.getFacetLocalNormals();
  17447. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17448. if (!facetsInBlock) {
  17449. return null;
  17450. }
  17451. // Get the closest facet to (x, y, z)
  17452. var shortest = Number.MAX_VALUE; // init distance vars
  17453. var tmpDistance = shortest;
  17454. var fib; // current facet in the block
  17455. var norm; // current facet normal
  17456. var p0; // current facet barycenter position
  17457. // loop on all the facets in the current partitioning block
  17458. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17459. fib = facetsInBlock[idx];
  17460. norm = facetNormals[fib];
  17461. p0 = facetPositions[fib];
  17462. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17463. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17464. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17465. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17466. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17467. projx = x + norm.x * t0;
  17468. projy = y + norm.y * t0;
  17469. projz = z + norm.z * t0;
  17470. tmpx = projx - x;
  17471. tmpy = projy - y;
  17472. tmpz = projz - z;
  17473. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17474. if (tmpDistance < shortest) {
  17475. shortest = tmpDistance;
  17476. closest = fib;
  17477. if (projected) {
  17478. projected.x = projx;
  17479. projected.y = projy;
  17480. projected.z = projz;
  17481. }
  17482. }
  17483. }
  17484. }
  17485. return closest;
  17486. };
  17487. /**
  17488. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17489. */
  17490. AbstractMesh.prototype.getFacetDataParameters = function () {
  17491. return this._facetParameters;
  17492. };
  17493. /**
  17494. * Disables the feature FacetData and frees the related memory.
  17495. * Returns the AbstractMesh.
  17496. */
  17497. AbstractMesh.prototype.disableFacetData = function () {
  17498. if (this._facetDataEnabled) {
  17499. this._facetDataEnabled = false;
  17500. this._facetPositions = new Array();
  17501. this._facetNormals = new Array();
  17502. this._facetPartitioning = new Array();
  17503. this._facetParameters = null;
  17504. this._depthSortedIndices = new Uint32Array(0);
  17505. }
  17506. return this;
  17507. };
  17508. /**
  17509. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17510. * Returns the mesh.
  17511. */
  17512. AbstractMesh.prototype.updateIndices = function (indices) {
  17513. return this;
  17514. };
  17515. /**
  17516. * The mesh Geometry. Actually used by the Mesh object.
  17517. * Returns a blank geometry object.
  17518. */
  17519. /**
  17520. * Creates new normals data for the mesh.
  17521. * @param updatable.
  17522. */
  17523. AbstractMesh.prototype.createNormals = function (updatable) {
  17524. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17525. var indices = this.getIndices();
  17526. var normals;
  17527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17528. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17529. }
  17530. else {
  17531. normals = [];
  17532. }
  17533. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17534. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17535. };
  17536. /**
  17537. * Align the mesh with a normal.
  17538. * Returns the mesh.
  17539. */
  17540. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17541. if (!upDirection) {
  17542. upDirection = BABYLON.Axis.Y;
  17543. }
  17544. var axisX = BABYLON.Tmp.Vector3[0];
  17545. var axisZ = BABYLON.Tmp.Vector3[1];
  17546. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17547. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17548. if (this.rotationQuaternion) {
  17549. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17550. }
  17551. else {
  17552. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17553. }
  17554. return this;
  17555. };
  17556. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17557. var engine = this.getEngine();
  17558. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17559. this._isOccluded = false;
  17560. return;
  17561. }
  17562. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17563. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17564. if (isOcclusionQueryAvailable) {
  17565. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17566. this._isOcclusionQueryInProgress = false;
  17567. this._occlusionInternalRetryCounter = 0;
  17568. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17569. }
  17570. else {
  17571. this._occlusionInternalRetryCounter++;
  17572. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17573. this._isOcclusionQueryInProgress = false;
  17574. this._occlusionInternalRetryCounter = 0;
  17575. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17576. // if strict continue the last state of the object.
  17577. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17578. }
  17579. else {
  17580. return;
  17581. }
  17582. }
  17583. }
  17584. var scene = this.getScene();
  17585. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17586. if (!this._occlusionQuery) {
  17587. this._occlusionQuery = engine.createQuery();
  17588. }
  17589. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17590. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17591. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17592. this._isOcclusionQueryInProgress = true;
  17593. };
  17594. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17595. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17596. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17597. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17598. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17599. return AbstractMesh;
  17600. }(BABYLON.TransformNode));
  17601. BABYLON.AbstractMesh = AbstractMesh;
  17602. })(BABYLON || (BABYLON = {}));
  17603. //# sourceMappingURL=babylon.abstractMesh.js.map
  17604. var BABYLON;
  17605. (function (BABYLON) {
  17606. /**
  17607. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  17608. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  17609. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  17610. */
  17611. var Light = /** @class */ (function (_super) {
  17612. __extends(Light, _super);
  17613. /**
  17614. * Creates a Light object in the scene.
  17615. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17616. * @param name The firendly name of the light
  17617. * @param scene The scene the light belongs too
  17618. */
  17619. function Light(name, scene) {
  17620. var _this = _super.call(this, name, scene) || this;
  17621. /**
  17622. * Diffuse gives the basic color to an object.
  17623. */
  17624. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17625. /**
  17626. * Specular produces a highlight color on an object.
  17627. * Note: This is note affecting PBR materials.
  17628. */
  17629. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17630. /**
  17631. * Strength of the light.
  17632. * Note: By default it is define in the framework own unit.
  17633. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  17634. */
  17635. _this.intensity = 1.0;
  17636. /**
  17637. * Defines how far from the source the light is impacting in scene units.
  17638. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  17639. */
  17640. _this.range = Number.MAX_VALUE;
  17641. /**
  17642. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17643. * of light.
  17644. */
  17645. _this._photometricScale = 1.0;
  17646. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17647. _this._radius = 0.00001;
  17648. /**
  17649. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  17650. * exceeding the number allowed of the materials.
  17651. */
  17652. _this.renderPriority = 0;
  17653. /**
  17654. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17655. * the current shadow generator.
  17656. */
  17657. _this.shadowEnabled = true;
  17658. _this._excludeWithLayerMask = 0;
  17659. _this._includeOnlyWithLayerMask = 0;
  17660. _this._lightmapMode = 0;
  17661. /**
  17662. * @ignore Internal use only.
  17663. */
  17664. _this._excludedMeshesIds = new Array();
  17665. /**
  17666. * @ignore Internal use only.
  17667. */
  17668. _this._includedOnlyMeshesIds = new Array();
  17669. _this.getScene().addLight(_this);
  17670. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17671. _this._buildUniformLayout();
  17672. _this.includedOnlyMeshes = new Array();
  17673. _this.excludedMeshes = new Array();
  17674. _this._resyncMeshes();
  17675. return _this;
  17676. }
  17677. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17678. /**
  17679. * If every light affecting the material is in this lightmapMode,
  17680. * material.lightmapTexture adds or multiplies
  17681. * (depends on material.useLightmapAsShadowmap)
  17682. * after every other light calculations.
  17683. */
  17684. get: function () {
  17685. return Light._LIGHTMAP_DEFAULT;
  17686. },
  17687. enumerable: true,
  17688. configurable: true
  17689. });
  17690. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17691. /**
  17692. * material.lightmapTexture as only diffuse lighting from this light
  17693. * adds only specular lighting from this light
  17694. * adds dynamic shadows
  17695. */
  17696. get: function () {
  17697. return Light._LIGHTMAP_SPECULAR;
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17703. /**
  17704. * material.lightmapTexture as only lighting
  17705. * no light calculation from this light
  17706. * only adds dynamic shadows from this light
  17707. */
  17708. get: function () {
  17709. return Light._LIGHTMAP_SHADOWSONLY;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17715. /**
  17716. * Each light type uses the default quantity according to its type:
  17717. * point/spot lights use luminous intensity
  17718. * directional lights use illuminance
  17719. */
  17720. get: function () {
  17721. return Light._INTENSITYMODE_AUTOMATIC;
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17727. /**
  17728. * lumen (lm)
  17729. */
  17730. get: function () {
  17731. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17732. },
  17733. enumerable: true,
  17734. configurable: true
  17735. });
  17736. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17737. /**
  17738. * candela (lm/sr)
  17739. */
  17740. get: function () {
  17741. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17747. /**
  17748. * lux (lm/m^2)
  17749. */
  17750. get: function () {
  17751. return Light._INTENSITYMODE_ILLUMINANCE;
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17757. /**
  17758. * nit (cd/m^2)
  17759. */
  17760. get: function () {
  17761. return Light._INTENSITYMODE_LUMINANCE;
  17762. },
  17763. enumerable: true,
  17764. configurable: true
  17765. });
  17766. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17767. /**
  17768. * Light type const id of the point light.
  17769. */
  17770. get: function () {
  17771. return Light._LIGHTTYPEID_POINTLIGHT;
  17772. },
  17773. enumerable: true,
  17774. configurable: true
  17775. });
  17776. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17777. /**
  17778. * Light type const id of the directional light.
  17779. */
  17780. get: function () {
  17781. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17782. },
  17783. enumerable: true,
  17784. configurable: true
  17785. });
  17786. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17787. /**
  17788. * Light type const id of the spot light.
  17789. */
  17790. get: function () {
  17791. return Light._LIGHTTYPEID_SPOTLIGHT;
  17792. },
  17793. enumerable: true,
  17794. configurable: true
  17795. });
  17796. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17797. /**
  17798. * Light type const id of the hemispheric light.
  17799. */
  17800. get: function () {
  17801. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17802. },
  17803. enumerable: true,
  17804. configurable: true
  17805. });
  17806. Object.defineProperty(Light.prototype, "intensityMode", {
  17807. /**
  17808. * Gets the photometric scale used to interpret the intensity.
  17809. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17810. */
  17811. get: function () {
  17812. return this._intensityMode;
  17813. },
  17814. /**
  17815. * Sets the photometric scale used to interpret the intensity.
  17816. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17817. */
  17818. set: function (value) {
  17819. this._intensityMode = value;
  17820. this._computePhotometricScale();
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. ;
  17826. ;
  17827. Object.defineProperty(Light.prototype, "radius", {
  17828. /**
  17829. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17830. */
  17831. get: function () {
  17832. return this._radius;
  17833. },
  17834. /**
  17835. * sets the light radius used by PBR Materials to simulate soft area lights.
  17836. */
  17837. set: function (value) {
  17838. this._radius = value;
  17839. this._computePhotometricScale();
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. ;
  17845. ;
  17846. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17847. /**
  17848. * Gets the only meshes impacted by this light.
  17849. */
  17850. get: function () {
  17851. return this._includedOnlyMeshes;
  17852. },
  17853. /**
  17854. * Sets the only meshes impacted by this light.
  17855. */
  17856. set: function (value) {
  17857. this._includedOnlyMeshes = value;
  17858. this._hookArrayForIncludedOnly(value);
  17859. },
  17860. enumerable: true,
  17861. configurable: true
  17862. });
  17863. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17864. /**
  17865. * Gets the meshes not impacted by this light.
  17866. */
  17867. get: function () {
  17868. return this._excludedMeshes;
  17869. },
  17870. /**
  17871. * Sets the meshes not impacted by this light.
  17872. */
  17873. set: function (value) {
  17874. this._excludedMeshes = value;
  17875. this._hookArrayForExcluded(value);
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17881. /**
  17882. * Gets the layer id use to find what meshes are not impacted by the light.
  17883. * Inactive if 0
  17884. */
  17885. get: function () {
  17886. return this._excludeWithLayerMask;
  17887. },
  17888. /**
  17889. * Sets the layer id use to find what meshes are not impacted by the light.
  17890. * Inactive if 0
  17891. */
  17892. set: function (value) {
  17893. this._excludeWithLayerMask = value;
  17894. this._resyncMeshes();
  17895. },
  17896. enumerable: true,
  17897. configurable: true
  17898. });
  17899. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17900. /**
  17901. * Gets the layer id use to find what meshes are impacted by the light.
  17902. * Inactive if 0
  17903. */
  17904. get: function () {
  17905. return this._includeOnlyWithLayerMask;
  17906. },
  17907. /**
  17908. * Sets the layer id use to find what meshes are impacted by the light.
  17909. * Inactive if 0
  17910. */
  17911. set: function (value) {
  17912. this._includeOnlyWithLayerMask = value;
  17913. this._resyncMeshes();
  17914. },
  17915. enumerable: true,
  17916. configurable: true
  17917. });
  17918. Object.defineProperty(Light.prototype, "lightmapMode", {
  17919. /**
  17920. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  17921. */
  17922. get: function () {
  17923. return this._lightmapMode;
  17924. },
  17925. /**
  17926. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  17927. */
  17928. set: function (value) {
  17929. if (this._lightmapMode === value) {
  17930. return;
  17931. }
  17932. this._lightmapMode = value;
  17933. this._markMeshesAsLightDirty();
  17934. },
  17935. enumerable: true,
  17936. configurable: true
  17937. });
  17938. /**
  17939. * Returns the string "Light".
  17940. * @returns the class name
  17941. */
  17942. Light.prototype.getClassName = function () {
  17943. return "Light";
  17944. };
  17945. /**
  17946. * Converts the light information to a readable string for debug purpose.
  17947. * @param fullDetails Supports for multiple levels of logging within scene loading
  17948. * @returns the human readable light info
  17949. */
  17950. Light.prototype.toString = function (fullDetails) {
  17951. var ret = "Name: " + this.name;
  17952. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17953. if (this.animations) {
  17954. for (var i = 0; i < this.animations.length; i++) {
  17955. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17956. }
  17957. }
  17958. if (fullDetails) {
  17959. }
  17960. return ret;
  17961. };
  17962. /**
  17963. * Set the enabled state of this node.
  17964. * @param value - the new enabled state
  17965. * @see isEnabled
  17966. */
  17967. Light.prototype.setEnabled = function (value) {
  17968. _super.prototype.setEnabled.call(this, value);
  17969. this._resyncMeshes();
  17970. };
  17971. /**
  17972. * Returns the Light associated shadow generator if any.
  17973. * @return the associated shadow generator.
  17974. */
  17975. Light.prototype.getShadowGenerator = function () {
  17976. return this._shadowGenerator;
  17977. };
  17978. /**
  17979. * Returns a Vector3, the absolute light position in the World.
  17980. * @returns the world space position of the light
  17981. */
  17982. Light.prototype.getAbsolutePosition = function () {
  17983. return BABYLON.Vector3.Zero();
  17984. };
  17985. /**
  17986. * Specifies if the light will affect the passed mesh.
  17987. * @param mesh The mesh to test against the light
  17988. * @return true the mesh is affected otherwise, false.
  17989. */
  17990. Light.prototype.canAffectMesh = function (mesh) {
  17991. if (!mesh) {
  17992. return true;
  17993. }
  17994. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17995. return false;
  17996. }
  17997. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17998. return false;
  17999. }
  18000. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18001. return false;
  18002. }
  18003. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18004. return false;
  18005. }
  18006. return true;
  18007. };
  18008. /**
  18009. * Computes and Returns the light World matrix.
  18010. * @returns the world matrix
  18011. */
  18012. Light.prototype.getWorldMatrix = function () {
  18013. this._currentRenderId = this.getScene().getRenderId();
  18014. var worldMatrix = this._getWorldMatrix();
  18015. if (this.parent && this.parent.getWorldMatrix) {
  18016. if (!this._parentedWorldMatrix) {
  18017. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18018. }
  18019. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18020. this._markSyncedWithParent();
  18021. return this._parentedWorldMatrix;
  18022. }
  18023. return worldMatrix;
  18024. };
  18025. /**
  18026. * Sort function to order lights for rendering.
  18027. * @param a First Light object to compare to second.
  18028. * @param b Second Light object to compare first.
  18029. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18030. */
  18031. Light.CompareLightsPriority = function (a, b) {
  18032. //shadow-casting lights have priority over non-shadow-casting lights
  18033. //the renderPrioirty is a secondary sort criterion
  18034. if (a.shadowEnabled !== b.shadowEnabled) {
  18035. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18036. }
  18037. return b.renderPriority - a.renderPriority;
  18038. };
  18039. /**
  18040. * Disposes the light.
  18041. */
  18042. Light.prototype.dispose = function () {
  18043. if (this._shadowGenerator) {
  18044. this._shadowGenerator.dispose();
  18045. this._shadowGenerator = null;
  18046. }
  18047. // Animations
  18048. this.getScene().stopAnimation(this);
  18049. // Remove from meshes
  18050. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18051. var mesh = _a[_i];
  18052. mesh._removeLightSource(this);
  18053. }
  18054. this._uniformBuffer.dispose();
  18055. // Remove from scene
  18056. this.getScene().removeLight(this);
  18057. _super.prototype.dispose.call(this);
  18058. };
  18059. /**
  18060. * Returns the light type ID (integer).
  18061. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18062. */
  18063. Light.prototype.getTypeID = function () {
  18064. return 0;
  18065. };
  18066. /**
  18067. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18068. * @returns the scaled intensity in intensity mode unit
  18069. */
  18070. Light.prototype.getScaledIntensity = function () {
  18071. return this._photometricScale * this.intensity;
  18072. };
  18073. /**
  18074. * Returns a new Light object, named "name", from the current one.
  18075. * @param name The name of the cloned light
  18076. * @returns the new created light
  18077. */
  18078. Light.prototype.clone = function (name) {
  18079. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18080. if (!constructor) {
  18081. return null;
  18082. }
  18083. return BABYLON.SerializationHelper.Clone(constructor, this);
  18084. };
  18085. /**
  18086. * Serializes the current light into a Serialization object.
  18087. * @returns the serialized object.
  18088. */
  18089. Light.prototype.serialize = function () {
  18090. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18091. // Type
  18092. serializationObject.type = this.getTypeID();
  18093. // Parent
  18094. if (this.parent) {
  18095. serializationObject.parentId = this.parent.id;
  18096. }
  18097. // Inclusion / exclusions
  18098. if (this.excludedMeshes.length > 0) {
  18099. serializationObject.excludedMeshesIds = [];
  18100. this.excludedMeshes.forEach(function (mesh) {
  18101. serializationObject.excludedMeshesIds.push(mesh.id);
  18102. });
  18103. }
  18104. if (this.includedOnlyMeshes.length > 0) {
  18105. serializationObject.includedOnlyMeshesIds = [];
  18106. this.includedOnlyMeshes.forEach(function (mesh) {
  18107. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18108. });
  18109. }
  18110. // Animations
  18111. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18112. serializationObject.ranges = this.serializeAnimationRanges();
  18113. return serializationObject;
  18114. };
  18115. /**
  18116. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18117. * This new light is named "name" and added to the passed scene.
  18118. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18119. * @param name The friendly name of the light
  18120. * @param scene The scene the new light will belong to
  18121. * @returns the constructor function
  18122. */
  18123. Light.GetConstructorFromName = function (type, name, scene) {
  18124. switch (type) {
  18125. case 0:
  18126. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18127. case 1:
  18128. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18129. case 2:
  18130. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18131. case 3:
  18132. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18133. }
  18134. return null;
  18135. };
  18136. /**
  18137. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18138. * @param parsedLight The JSON representation of the light
  18139. * @param scene The scene to create the parsed light in
  18140. * @returns the created light after parsing
  18141. */
  18142. Light.Parse = function (parsedLight, scene) {
  18143. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18144. if (!constructor) {
  18145. return null;
  18146. }
  18147. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18148. // Inclusion / exclusions
  18149. if (parsedLight.excludedMeshesIds) {
  18150. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18151. }
  18152. if (parsedLight.includedOnlyMeshesIds) {
  18153. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18154. }
  18155. // Parent
  18156. if (parsedLight.parentId) {
  18157. light._waitingParentId = parsedLight.parentId;
  18158. }
  18159. // Animations
  18160. if (parsedLight.animations) {
  18161. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18162. var parsedAnimation = parsedLight.animations[animationIndex];
  18163. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18164. }
  18165. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18166. }
  18167. if (parsedLight.autoAnimate) {
  18168. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18169. }
  18170. return light;
  18171. };
  18172. Light.prototype._hookArrayForExcluded = function (array) {
  18173. var _this = this;
  18174. var oldPush = array.push;
  18175. array.push = function () {
  18176. var items = [];
  18177. for (var _i = 0; _i < arguments.length; _i++) {
  18178. items[_i] = arguments[_i];
  18179. }
  18180. var result = oldPush.apply(array, items);
  18181. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18182. var item = items_1[_a];
  18183. item._resyncLighSource(_this);
  18184. }
  18185. return result;
  18186. };
  18187. var oldSplice = array.splice;
  18188. array.splice = function (index, deleteCount) {
  18189. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18190. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18191. var item = deleted_1[_i];
  18192. item._resyncLighSource(_this);
  18193. }
  18194. return deleted;
  18195. };
  18196. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18197. var item = array_1[_i];
  18198. item._resyncLighSource(this);
  18199. }
  18200. };
  18201. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18202. var _this = this;
  18203. var oldPush = array.push;
  18204. array.push = function () {
  18205. var items = [];
  18206. for (var _i = 0; _i < arguments.length; _i++) {
  18207. items[_i] = arguments[_i];
  18208. }
  18209. var result = oldPush.apply(array, items);
  18210. _this._resyncMeshes();
  18211. return result;
  18212. };
  18213. var oldSplice = array.splice;
  18214. array.splice = function (index, deleteCount) {
  18215. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18216. _this._resyncMeshes();
  18217. return deleted;
  18218. };
  18219. this._resyncMeshes();
  18220. };
  18221. Light.prototype._resyncMeshes = function () {
  18222. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18223. var mesh = _a[_i];
  18224. mesh._resyncLighSource(this);
  18225. }
  18226. };
  18227. /**
  18228. * Forces the meshes to update their light related information in their rendering used effects
  18229. * @ignore Internal Use Only
  18230. */
  18231. Light.prototype._markMeshesAsLightDirty = function () {
  18232. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18233. var mesh = _a[_i];
  18234. if (mesh._lightSources.indexOf(this) !== -1) {
  18235. mesh._markSubMeshesAsLightDirty();
  18236. }
  18237. }
  18238. };
  18239. /**
  18240. * Recomputes the cached photometric scale if needed.
  18241. */
  18242. Light.prototype._computePhotometricScale = function () {
  18243. this._photometricScale = this._getPhotometricScale();
  18244. this.getScene().resetCachedMaterial();
  18245. };
  18246. /**
  18247. * Returns the Photometric Scale according to the light type and intensity mode.
  18248. */
  18249. Light.prototype._getPhotometricScale = function () {
  18250. var photometricScale = 0.0;
  18251. var lightTypeID = this.getTypeID();
  18252. //get photometric mode
  18253. var photometricMode = this.intensityMode;
  18254. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18255. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18256. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18257. }
  18258. else {
  18259. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18260. }
  18261. }
  18262. //compute photometric scale
  18263. switch (lightTypeID) {
  18264. case Light.LIGHTTYPEID_POINTLIGHT:
  18265. case Light.LIGHTTYPEID_SPOTLIGHT:
  18266. switch (photometricMode) {
  18267. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18268. photometricScale = 1.0 / (4.0 * Math.PI);
  18269. break;
  18270. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18271. photometricScale = 1.0;
  18272. break;
  18273. case Light.INTENSITYMODE_LUMINANCE:
  18274. photometricScale = this.radius * this.radius;
  18275. break;
  18276. }
  18277. break;
  18278. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18279. switch (photometricMode) {
  18280. case Light.INTENSITYMODE_ILLUMINANCE:
  18281. photometricScale = 1.0;
  18282. break;
  18283. case Light.INTENSITYMODE_LUMINANCE:
  18284. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18285. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18286. var apexAngleRadians = this.radius;
  18287. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18288. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18289. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18290. photometricScale = solidAngle;
  18291. break;
  18292. }
  18293. break;
  18294. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18295. // No fall off in hemisperic light.
  18296. photometricScale = 1.0;
  18297. break;
  18298. }
  18299. return photometricScale;
  18300. };
  18301. /**
  18302. * Reorder the light in the scene according to their defined priority.
  18303. * @ignore Internal Use Only
  18304. */
  18305. Light.prototype._reorderLightsInScene = function () {
  18306. var scene = this.getScene();
  18307. if (this._renderPriority != 0) {
  18308. scene.requireLightSorting = true;
  18309. }
  18310. this.getScene().sortLightsByPriority();
  18311. };
  18312. //lightmapMode Consts
  18313. Light._LIGHTMAP_DEFAULT = 0;
  18314. Light._LIGHTMAP_SPECULAR = 1;
  18315. Light._LIGHTMAP_SHADOWSONLY = 2;
  18316. // Intensity Mode Consts
  18317. Light._INTENSITYMODE_AUTOMATIC = 0;
  18318. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  18319. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  18320. Light._INTENSITYMODE_ILLUMINANCE = 3;
  18321. Light._INTENSITYMODE_LUMINANCE = 4;
  18322. // Light types ids const.
  18323. Light._LIGHTTYPEID_POINTLIGHT = 0;
  18324. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  18325. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  18326. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  18327. __decorate([
  18328. BABYLON.serializeAsColor3()
  18329. ], Light.prototype, "diffuse", void 0);
  18330. __decorate([
  18331. BABYLON.serializeAsColor3()
  18332. ], Light.prototype, "specular", void 0);
  18333. __decorate([
  18334. BABYLON.serialize()
  18335. ], Light.prototype, "intensity", void 0);
  18336. __decorate([
  18337. BABYLON.serialize()
  18338. ], Light.prototype, "range", void 0);
  18339. __decorate([
  18340. BABYLON.serialize()
  18341. ], Light.prototype, "intensityMode", null);
  18342. __decorate([
  18343. BABYLON.serialize()
  18344. ], Light.prototype, "radius", null);
  18345. __decorate([
  18346. BABYLON.serialize()
  18347. ], Light.prototype, "_renderPriority", void 0);
  18348. __decorate([
  18349. BABYLON.expandToProperty("_reorderLightsInScene")
  18350. ], Light.prototype, "renderPriority", void 0);
  18351. __decorate([
  18352. BABYLON.serialize()
  18353. ], Light.prototype, "shadowEnabled", void 0);
  18354. __decorate([
  18355. BABYLON.serialize("excludeWithLayerMask")
  18356. ], Light.prototype, "_excludeWithLayerMask", void 0);
  18357. __decorate([
  18358. BABYLON.serialize("includeOnlyWithLayerMask")
  18359. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  18360. __decorate([
  18361. BABYLON.serialize("lightmapMode")
  18362. ], Light.prototype, "_lightmapMode", void 0);
  18363. return Light;
  18364. }(BABYLON.Node));
  18365. BABYLON.Light = Light;
  18366. })(BABYLON || (BABYLON = {}));
  18367. //# sourceMappingURL=babylon.light.js.map
  18368. var BABYLON;
  18369. (function (BABYLON) {
  18370. var Camera = /** @class */ (function (_super) {
  18371. __extends(Camera, _super);
  18372. function Camera(name, position, scene) {
  18373. var _this = _super.call(this, name, scene) || this;
  18374. /**
  18375. * The vector the camera should consider as up.
  18376. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18377. */
  18378. _this.upVector = BABYLON.Vector3.Up();
  18379. _this.orthoLeft = null;
  18380. _this.orthoRight = null;
  18381. _this.orthoBottom = null;
  18382. _this.orthoTop = null;
  18383. /**
  18384. * FOV is set in Radians. (default is 0.8)
  18385. */
  18386. _this.fov = 0.8;
  18387. _this.minZ = 1;
  18388. _this.maxZ = 10000.0;
  18389. _this.inertia = 0.9;
  18390. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18391. _this.isIntermediate = false;
  18392. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18393. /**
  18394. * Restricts the camera to viewing objects with the same layerMask.
  18395. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18396. */
  18397. _this.layerMask = 0x0FFFFFFF;
  18398. /**
  18399. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18400. */
  18401. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18402. // Camera rig members
  18403. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18404. _this._rigCameras = new Array();
  18405. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18406. _this._skipRendering = false;
  18407. _this.customRenderTargets = new Array();
  18408. // Observables
  18409. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18410. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18411. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18412. _this.onRestoreStateObservable = new BABYLON.Observable();
  18413. // Cache
  18414. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18415. _this._projectionMatrix = new BABYLON.Matrix();
  18416. _this._doNotComputeProjectionMatrix = false;
  18417. _this._postProcesses = new Array();
  18418. _this._transformMatrix = BABYLON.Matrix.Zero();
  18419. _this._activeMeshes = new BABYLON.SmartArray(256);
  18420. _this._globalPosition = BABYLON.Vector3.Zero();
  18421. _this._refreshFrustumPlanes = true;
  18422. _this.getScene().addCamera(_this);
  18423. if (!_this.getScene().activeCamera) {
  18424. _this.getScene().activeCamera = _this;
  18425. }
  18426. _this.position = position;
  18427. return _this;
  18428. }
  18429. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18430. get: function () {
  18431. return Camera._PERSPECTIVE_CAMERA;
  18432. },
  18433. enumerable: true,
  18434. configurable: true
  18435. });
  18436. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18437. get: function () {
  18438. return Camera._ORTHOGRAPHIC_CAMERA;
  18439. },
  18440. enumerable: true,
  18441. configurable: true
  18442. });
  18443. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18444. /**
  18445. * This is the default FOV mode for perspective cameras.
  18446. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18447. *
  18448. */
  18449. get: function () {
  18450. return Camera._FOVMODE_VERTICAL_FIXED;
  18451. },
  18452. enumerable: true,
  18453. configurable: true
  18454. });
  18455. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18456. /**
  18457. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18458. *
  18459. */
  18460. get: function () {
  18461. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18462. },
  18463. enumerable: true,
  18464. configurable: true
  18465. });
  18466. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18467. get: function () {
  18468. return Camera._RIG_MODE_NONE;
  18469. },
  18470. enumerable: true,
  18471. configurable: true
  18472. });
  18473. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18474. get: function () {
  18475. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18481. get: function () {
  18482. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18488. get: function () {
  18489. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18490. },
  18491. enumerable: true,
  18492. configurable: true
  18493. });
  18494. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18495. get: function () {
  18496. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18502. get: function () {
  18503. return Camera._RIG_MODE_VR;
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18509. get: function () {
  18510. return Camera._RIG_MODE_WEBVR;
  18511. },
  18512. enumerable: true,
  18513. configurable: true
  18514. });
  18515. /**
  18516. * Store current camera state (fov, position, etc..)
  18517. */
  18518. Camera.prototype.storeState = function () {
  18519. this._stateStored = true;
  18520. this._storedFov = this.fov;
  18521. return this;
  18522. };
  18523. /**
  18524. * Restores the camera state values if it has been stored. You must call storeState() first
  18525. */
  18526. Camera.prototype._restoreStateValues = function () {
  18527. if (!this._stateStored) {
  18528. return false;
  18529. }
  18530. this.fov = this._storedFov;
  18531. return true;
  18532. };
  18533. /**
  18534. * Restored camera state. You must call storeState() first
  18535. */
  18536. Camera.prototype.restoreState = function () {
  18537. if (this._restoreStateValues()) {
  18538. this.onRestoreStateObservable.notifyObservers(this);
  18539. return true;
  18540. }
  18541. return false;
  18542. };
  18543. Camera.prototype.getClassName = function () {
  18544. return "Camera";
  18545. };
  18546. /**
  18547. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18548. */
  18549. Camera.prototype.toString = function (fullDetails) {
  18550. var ret = "Name: " + this.name;
  18551. ret += ", type: " + this.getClassName();
  18552. if (this.animations) {
  18553. for (var i = 0; i < this.animations.length; i++) {
  18554. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18555. }
  18556. }
  18557. if (fullDetails) {
  18558. }
  18559. return ret;
  18560. };
  18561. Object.defineProperty(Camera.prototype, "globalPosition", {
  18562. get: function () {
  18563. return this._globalPosition;
  18564. },
  18565. enumerable: true,
  18566. configurable: true
  18567. });
  18568. Camera.prototype.getActiveMeshes = function () {
  18569. return this._activeMeshes;
  18570. };
  18571. Camera.prototype.isActiveMesh = function (mesh) {
  18572. return (this._activeMeshes.indexOf(mesh) !== -1);
  18573. };
  18574. //Cache
  18575. Camera.prototype._initCache = function () {
  18576. _super.prototype._initCache.call(this);
  18577. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18578. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18579. this._cache.mode = undefined;
  18580. this._cache.minZ = undefined;
  18581. this._cache.maxZ = undefined;
  18582. this._cache.fov = undefined;
  18583. this._cache.fovMode = undefined;
  18584. this._cache.aspectRatio = undefined;
  18585. this._cache.orthoLeft = undefined;
  18586. this._cache.orthoRight = undefined;
  18587. this._cache.orthoBottom = undefined;
  18588. this._cache.orthoTop = undefined;
  18589. this._cache.renderWidth = undefined;
  18590. this._cache.renderHeight = undefined;
  18591. };
  18592. Camera.prototype._updateCache = function (ignoreParentClass) {
  18593. if (!ignoreParentClass) {
  18594. _super.prototype._updateCache.call(this);
  18595. }
  18596. this._cache.position.copyFrom(this.position);
  18597. this._cache.upVector.copyFrom(this.upVector);
  18598. };
  18599. // Synchronized
  18600. Camera.prototype._isSynchronized = function () {
  18601. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18602. };
  18603. Camera.prototype._isSynchronizedViewMatrix = function () {
  18604. if (!_super.prototype._isSynchronized.call(this))
  18605. return false;
  18606. return this._cache.position.equals(this.position)
  18607. && this._cache.upVector.equals(this.upVector)
  18608. && this.isSynchronizedWithParent();
  18609. };
  18610. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18611. var check = this._cache.mode === this.mode
  18612. && this._cache.minZ === this.minZ
  18613. && this._cache.maxZ === this.maxZ;
  18614. if (!check) {
  18615. return false;
  18616. }
  18617. var engine = this.getEngine();
  18618. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18619. check = this._cache.fov === this.fov
  18620. && this._cache.fovMode === this.fovMode
  18621. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18622. }
  18623. else {
  18624. check = this._cache.orthoLeft === this.orthoLeft
  18625. && this._cache.orthoRight === this.orthoRight
  18626. && this._cache.orthoBottom === this.orthoBottom
  18627. && this._cache.orthoTop === this.orthoTop
  18628. && this._cache.renderWidth === engine.getRenderWidth()
  18629. && this._cache.renderHeight === engine.getRenderHeight();
  18630. }
  18631. return check;
  18632. };
  18633. // Controls
  18634. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18635. };
  18636. Camera.prototype.detachControl = function (element) {
  18637. };
  18638. Camera.prototype.update = function () {
  18639. this._checkInputs();
  18640. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18641. this._updateRigCameras();
  18642. }
  18643. };
  18644. Camera.prototype._checkInputs = function () {
  18645. this.onAfterCheckInputsObservable.notifyObservers(this);
  18646. };
  18647. Object.defineProperty(Camera.prototype, "rigCameras", {
  18648. get: function () {
  18649. return this._rigCameras;
  18650. },
  18651. enumerable: true,
  18652. configurable: true
  18653. });
  18654. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18655. get: function () {
  18656. return this._rigPostProcess;
  18657. },
  18658. enumerable: true,
  18659. configurable: true
  18660. });
  18661. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18662. // invalidate framebuffer
  18663. if (this._postProcesses.length > 0) {
  18664. this._postProcesses[0].markTextureDirty();
  18665. }
  18666. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18667. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18668. var cam = this._rigCameras[i];
  18669. var rigPostProcess = cam._rigPostProcess;
  18670. // for VR rig, there does not have to be a post process
  18671. if (rigPostProcess) {
  18672. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18673. if (isPass) {
  18674. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18675. cam.isIntermediate = this._postProcesses.length === 0;
  18676. }
  18677. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18678. rigPostProcess.markTextureDirty();
  18679. }
  18680. else {
  18681. cam._postProcesses = this._postProcesses.slice(0);
  18682. }
  18683. }
  18684. };
  18685. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18686. if (insertAt === void 0) { insertAt = null; }
  18687. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18688. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18689. return 0;
  18690. }
  18691. if (insertAt == null || insertAt < 0) {
  18692. this._postProcesses.push(postProcess);
  18693. }
  18694. else {
  18695. this._postProcesses.splice(insertAt, 0, postProcess);
  18696. }
  18697. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18698. return this._postProcesses.indexOf(postProcess);
  18699. };
  18700. Camera.prototype.detachPostProcess = function (postProcess) {
  18701. var idx = this._postProcesses.indexOf(postProcess);
  18702. if (idx !== -1) {
  18703. this._postProcesses.splice(idx, 1);
  18704. }
  18705. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18706. };
  18707. Camera.prototype.getWorldMatrix = function () {
  18708. if (!this._worldMatrix) {
  18709. this._worldMatrix = BABYLON.Matrix.Identity();
  18710. }
  18711. var viewMatrix = this.getViewMatrix();
  18712. viewMatrix.invertToRef(this._worldMatrix);
  18713. return this._worldMatrix;
  18714. };
  18715. Camera.prototype._getViewMatrix = function () {
  18716. return BABYLON.Matrix.Identity();
  18717. };
  18718. Camera.prototype.getViewMatrix = function (force) {
  18719. if (!force && this._isSynchronizedViewMatrix()) {
  18720. return this._computedViewMatrix;
  18721. }
  18722. this.updateCache();
  18723. this._computedViewMatrix = this._getViewMatrix();
  18724. this._currentRenderId = this.getScene().getRenderId();
  18725. this._refreshFrustumPlanes = true;
  18726. if (!this.parent || !this.parent.getWorldMatrix) {
  18727. this._globalPosition.copyFrom(this.position);
  18728. }
  18729. else {
  18730. if (!this._worldMatrix) {
  18731. this._worldMatrix = BABYLON.Matrix.Identity();
  18732. }
  18733. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18734. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18735. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18736. this._computedViewMatrix.invert();
  18737. this._markSyncedWithParent();
  18738. }
  18739. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18740. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18741. }
  18742. this.onViewMatrixChangedObservable.notifyObservers(this);
  18743. return this._computedViewMatrix;
  18744. };
  18745. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18746. this._doNotComputeProjectionMatrix = true;
  18747. if (projection !== undefined) {
  18748. this._projectionMatrix = projection;
  18749. }
  18750. };
  18751. ;
  18752. Camera.prototype.unfreezeProjectionMatrix = function () {
  18753. this._doNotComputeProjectionMatrix = false;
  18754. };
  18755. ;
  18756. Camera.prototype.getProjectionMatrix = function (force) {
  18757. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18758. return this._projectionMatrix;
  18759. }
  18760. // Cache
  18761. this._cache.mode = this.mode;
  18762. this._cache.minZ = this.minZ;
  18763. this._cache.maxZ = this.maxZ;
  18764. // Matrix
  18765. this._refreshFrustumPlanes = true;
  18766. var engine = this.getEngine();
  18767. var scene = this.getScene();
  18768. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18769. this._cache.fov = this.fov;
  18770. this._cache.fovMode = this.fovMode;
  18771. this._cache.aspectRatio = engine.getAspectRatio(this);
  18772. if (this.minZ <= 0) {
  18773. this.minZ = 0.1;
  18774. }
  18775. if (scene.useRightHandedSystem) {
  18776. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18777. }
  18778. else {
  18779. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18780. }
  18781. }
  18782. else {
  18783. var halfWidth = engine.getRenderWidth() / 2.0;
  18784. var halfHeight = engine.getRenderHeight() / 2.0;
  18785. if (scene.useRightHandedSystem) {
  18786. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18787. }
  18788. else {
  18789. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18790. }
  18791. this._cache.orthoLeft = this.orthoLeft;
  18792. this._cache.orthoRight = this.orthoRight;
  18793. this._cache.orthoBottom = this.orthoBottom;
  18794. this._cache.orthoTop = this.orthoTop;
  18795. this._cache.renderWidth = engine.getRenderWidth();
  18796. this._cache.renderHeight = engine.getRenderHeight();
  18797. }
  18798. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18799. return this._projectionMatrix;
  18800. };
  18801. Camera.prototype.getTranformationMatrix = function () {
  18802. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18803. return this._transformMatrix;
  18804. };
  18805. Camera.prototype.updateFrustumPlanes = function () {
  18806. if (!this._refreshFrustumPlanes) {
  18807. return;
  18808. }
  18809. this.getTranformationMatrix();
  18810. if (!this._frustumPlanes) {
  18811. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18812. }
  18813. else {
  18814. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18815. }
  18816. this._refreshFrustumPlanes = false;
  18817. };
  18818. Camera.prototype.isInFrustum = function (target) {
  18819. this.updateFrustumPlanes();
  18820. return target.isInFrustum(this._frustumPlanes);
  18821. };
  18822. Camera.prototype.isCompletelyInFrustum = function (target) {
  18823. this.updateFrustumPlanes();
  18824. return target.isCompletelyInFrustum(this._frustumPlanes);
  18825. };
  18826. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18827. if (length === void 0) { length = 100; }
  18828. if (!transform) {
  18829. transform = this.getWorldMatrix();
  18830. }
  18831. if (!origin) {
  18832. origin = this.position;
  18833. }
  18834. var forward = new BABYLON.Vector3(0, 0, 1);
  18835. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18836. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18837. return new BABYLON.Ray(origin, direction, length);
  18838. };
  18839. Camera.prototype.dispose = function () {
  18840. // Observables
  18841. this.onViewMatrixChangedObservable.clear();
  18842. this.onProjectionMatrixChangedObservable.clear();
  18843. this.onAfterCheckInputsObservable.clear();
  18844. this.onRestoreStateObservable.clear();
  18845. // Inputs
  18846. if (this.inputs) {
  18847. this.inputs.clear();
  18848. }
  18849. // Animations
  18850. this.getScene().stopAnimation(this);
  18851. // Remove from scene
  18852. this.getScene().removeCamera(this);
  18853. while (this._rigCameras.length > 0) {
  18854. var camera = this._rigCameras.pop();
  18855. if (camera) {
  18856. camera.dispose();
  18857. }
  18858. }
  18859. // Postprocesses
  18860. if (this._rigPostProcess) {
  18861. this._rigPostProcess.dispose(this);
  18862. this._rigPostProcess = null;
  18863. this._postProcesses = [];
  18864. }
  18865. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18866. this._rigPostProcess = null;
  18867. this._postProcesses = [];
  18868. }
  18869. else {
  18870. var i = this._postProcesses.length;
  18871. while (--i >= 0) {
  18872. this._postProcesses[i].dispose(this);
  18873. }
  18874. }
  18875. // Render targets
  18876. var i = this.customRenderTargets.length;
  18877. while (--i >= 0) {
  18878. this.customRenderTargets[i].dispose();
  18879. }
  18880. this.customRenderTargets = [];
  18881. // Active Meshes
  18882. this._activeMeshes.dispose();
  18883. _super.prototype.dispose.call(this);
  18884. };
  18885. Object.defineProperty(Camera.prototype, "leftCamera", {
  18886. // ---- Camera rigs section ----
  18887. get: function () {
  18888. if (this._rigCameras.length < 1) {
  18889. return null;
  18890. }
  18891. return this._rigCameras[0];
  18892. },
  18893. enumerable: true,
  18894. configurable: true
  18895. });
  18896. Object.defineProperty(Camera.prototype, "rightCamera", {
  18897. get: function () {
  18898. if (this._rigCameras.length < 2) {
  18899. return null;
  18900. }
  18901. return this._rigCameras[1];
  18902. },
  18903. enumerable: true,
  18904. configurable: true
  18905. });
  18906. Camera.prototype.getLeftTarget = function () {
  18907. if (this._rigCameras.length < 1) {
  18908. return null;
  18909. }
  18910. return this._rigCameras[0].getTarget();
  18911. };
  18912. Camera.prototype.getRightTarget = function () {
  18913. if (this._rigCameras.length < 2) {
  18914. return null;
  18915. }
  18916. return this._rigCameras[1].getTarget();
  18917. };
  18918. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18919. if (this.cameraRigMode === mode) {
  18920. return;
  18921. }
  18922. while (this._rigCameras.length > 0) {
  18923. var camera = this._rigCameras.pop();
  18924. if (camera) {
  18925. camera.dispose();
  18926. }
  18927. }
  18928. this.cameraRigMode = mode;
  18929. this._cameraRigParams = {};
  18930. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18931. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18932. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18933. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18934. // create the rig cameras, unless none
  18935. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18936. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18937. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18938. if (leftCamera && rightCamera) {
  18939. this._rigCameras.push(leftCamera);
  18940. this._rigCameras.push(rightCamera);
  18941. }
  18942. }
  18943. switch (this.cameraRigMode) {
  18944. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18945. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18946. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18947. break;
  18948. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18949. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18950. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18951. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18952. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18953. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18954. break;
  18955. case Camera.RIG_MODE_VR:
  18956. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18957. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18958. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18959. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18960. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18961. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18962. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18963. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18964. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18965. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18966. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18967. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18968. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18969. if (metrics.compensateDistortion) {
  18970. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18971. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18972. }
  18973. break;
  18974. case Camera.RIG_MODE_WEBVR:
  18975. if (rigParams.vrDisplay) {
  18976. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18977. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18978. //Left eye
  18979. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18980. this._rigCameras[0].setCameraRigParameter("left", true);
  18981. //leaving this for future reference
  18982. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18983. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18984. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18985. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18986. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18987. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18988. this._rigCameras[0].parent = this;
  18989. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18990. //Right eye
  18991. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18992. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18993. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18994. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18995. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18996. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18997. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18998. this._rigCameras[1].parent = this;
  18999. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19000. if (Camera.UseAlternateWebVRRendering) {
  19001. this._rigCameras[1]._skipRendering = true;
  19002. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19003. }
  19004. }
  19005. break;
  19006. }
  19007. this._cascadePostProcessesToRigCams();
  19008. this.update();
  19009. };
  19010. Camera.prototype._getVRProjectionMatrix = function () {
  19011. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19012. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19013. return this._projectionMatrix;
  19014. };
  19015. Camera.prototype._updateCameraRotationMatrix = function () {
  19016. //Here for WebVR
  19017. };
  19018. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19019. //Here for WebVR
  19020. };
  19021. /**
  19022. * This function MUST be overwritten by the different WebVR cameras available.
  19023. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19024. */
  19025. Camera.prototype._getWebVRProjectionMatrix = function () {
  19026. return BABYLON.Matrix.Identity();
  19027. };
  19028. /**
  19029. * This function MUST be overwritten by the different WebVR cameras available.
  19030. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19031. */
  19032. Camera.prototype._getWebVRViewMatrix = function () {
  19033. return BABYLON.Matrix.Identity();
  19034. };
  19035. Camera.prototype.setCameraRigParameter = function (name, value) {
  19036. if (!this._cameraRigParams) {
  19037. this._cameraRigParams = {};
  19038. }
  19039. this._cameraRigParams[name] = value;
  19040. //provisionnally:
  19041. if (name === "interaxialDistance") {
  19042. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19043. }
  19044. };
  19045. /**
  19046. * needs to be overridden by children so sub has required properties to be copied
  19047. */
  19048. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19049. return null;
  19050. };
  19051. /**
  19052. * May need to be overridden by children
  19053. */
  19054. Camera.prototype._updateRigCameras = function () {
  19055. for (var i = 0; i < this._rigCameras.length; i++) {
  19056. this._rigCameras[i].minZ = this.minZ;
  19057. this._rigCameras[i].maxZ = this.maxZ;
  19058. this._rigCameras[i].fov = this.fov;
  19059. }
  19060. // only update viewport when ANAGLYPH
  19061. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19062. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19063. }
  19064. };
  19065. Camera.prototype._setupInputs = function () {
  19066. };
  19067. Camera.prototype.serialize = function () {
  19068. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19069. // Type
  19070. serializationObject.type = this.getClassName();
  19071. // Parent
  19072. if (this.parent) {
  19073. serializationObject.parentId = this.parent.id;
  19074. }
  19075. if (this.inputs) {
  19076. this.inputs.serialize(serializationObject);
  19077. }
  19078. // Animations
  19079. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19080. serializationObject.ranges = this.serializeAnimationRanges();
  19081. return serializationObject;
  19082. };
  19083. Camera.prototype.clone = function (name) {
  19084. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19085. };
  19086. Camera.prototype.getDirection = function (localAxis) {
  19087. var result = BABYLON.Vector3.Zero();
  19088. this.getDirectionToRef(localAxis, result);
  19089. return result;
  19090. };
  19091. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19092. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19093. };
  19094. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19095. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19096. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19097. switch (type) {
  19098. case "ArcRotateCamera":
  19099. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19100. case "DeviceOrientationCamera":
  19101. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19102. case "FollowCamera":
  19103. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19104. case "ArcFollowCamera":
  19105. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19106. case "GamepadCamera":
  19107. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19108. case "TouchCamera":
  19109. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19110. case "VirtualJoysticksCamera":
  19111. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19112. case "WebVRFreeCamera":
  19113. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19114. case "WebVRGamepadCamera":
  19115. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19116. case "VRDeviceOrientationFreeCamera":
  19117. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19118. case "VRDeviceOrientationGamepadCamera":
  19119. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19120. case "AnaglyphArcRotateCamera":
  19121. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19122. case "AnaglyphFreeCamera":
  19123. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19124. case "AnaglyphGamepadCamera":
  19125. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19126. case "AnaglyphUniversalCamera":
  19127. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19128. case "StereoscopicArcRotateCamera":
  19129. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19130. case "StereoscopicFreeCamera":
  19131. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19132. case "StereoscopicGamepadCamera":
  19133. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19134. case "StereoscopicUniversalCamera":
  19135. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19136. case "FreeCamera":// Forcing Universal here
  19137. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19138. default:// Universal Camera is the default value
  19139. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19140. }
  19141. };
  19142. Camera.prototype.computeWorldMatrix = function () {
  19143. return this.getWorldMatrix();
  19144. };
  19145. Camera.Parse = function (parsedCamera, scene) {
  19146. var type = parsedCamera.type;
  19147. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19148. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19149. // Parent
  19150. if (parsedCamera.parentId) {
  19151. camera._waitingParentId = parsedCamera.parentId;
  19152. }
  19153. //If camera has an input manager, let it parse inputs settings
  19154. if (camera.inputs) {
  19155. camera.inputs.parse(parsedCamera);
  19156. camera._setupInputs();
  19157. }
  19158. if (camera.setPosition) {
  19159. camera.position.copyFromFloats(0, 0, 0);
  19160. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19161. }
  19162. // Target
  19163. if (parsedCamera.target) {
  19164. if (camera.setTarget) {
  19165. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19166. }
  19167. }
  19168. // Apply 3d rig, when found
  19169. if (parsedCamera.cameraRigMode) {
  19170. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19171. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19172. }
  19173. // Animations
  19174. if (parsedCamera.animations) {
  19175. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19176. var parsedAnimation = parsedCamera.animations[animationIndex];
  19177. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19178. }
  19179. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19180. }
  19181. if (parsedCamera.autoAnimate) {
  19182. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19183. }
  19184. return camera;
  19185. };
  19186. // Statics
  19187. Camera._PERSPECTIVE_CAMERA = 0;
  19188. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19189. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19190. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19191. Camera._RIG_MODE_NONE = 0;
  19192. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19193. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19194. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19195. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19196. Camera._RIG_MODE_VR = 20;
  19197. Camera._RIG_MODE_WEBVR = 21;
  19198. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19199. Camera.UseAlternateWebVRRendering = false;
  19200. __decorate([
  19201. BABYLON.serializeAsVector3()
  19202. ], Camera.prototype, "position", void 0);
  19203. __decorate([
  19204. BABYLON.serializeAsVector3()
  19205. ], Camera.prototype, "upVector", void 0);
  19206. __decorate([
  19207. BABYLON.serialize()
  19208. ], Camera.prototype, "orthoLeft", void 0);
  19209. __decorate([
  19210. BABYLON.serialize()
  19211. ], Camera.prototype, "orthoRight", void 0);
  19212. __decorate([
  19213. BABYLON.serialize()
  19214. ], Camera.prototype, "orthoBottom", void 0);
  19215. __decorate([
  19216. BABYLON.serialize()
  19217. ], Camera.prototype, "orthoTop", void 0);
  19218. __decorate([
  19219. BABYLON.serialize()
  19220. ], Camera.prototype, "fov", void 0);
  19221. __decorate([
  19222. BABYLON.serialize()
  19223. ], Camera.prototype, "minZ", void 0);
  19224. __decorate([
  19225. BABYLON.serialize()
  19226. ], Camera.prototype, "maxZ", void 0);
  19227. __decorate([
  19228. BABYLON.serialize()
  19229. ], Camera.prototype, "inertia", void 0);
  19230. __decorate([
  19231. BABYLON.serialize()
  19232. ], Camera.prototype, "mode", void 0);
  19233. __decorate([
  19234. BABYLON.serialize()
  19235. ], Camera.prototype, "layerMask", void 0);
  19236. __decorate([
  19237. BABYLON.serialize()
  19238. ], Camera.prototype, "fovMode", void 0);
  19239. __decorate([
  19240. BABYLON.serialize()
  19241. ], Camera.prototype, "cameraRigMode", void 0);
  19242. __decorate([
  19243. BABYLON.serialize()
  19244. ], Camera.prototype, "interaxialDistance", void 0);
  19245. __decorate([
  19246. BABYLON.serialize()
  19247. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19248. return Camera;
  19249. }(BABYLON.Node));
  19250. BABYLON.Camera = Camera;
  19251. })(BABYLON || (BABYLON = {}));
  19252. //# sourceMappingURL=babylon.camera.js.map
  19253. var BABYLON;
  19254. (function (BABYLON) {
  19255. var RenderingManager = /** @class */ (function () {
  19256. function RenderingManager(scene) {
  19257. this._renderingGroups = new Array();
  19258. this._autoClearDepthStencil = {};
  19259. this._customOpaqueSortCompareFn = {};
  19260. this._customAlphaTestSortCompareFn = {};
  19261. this._customTransparentSortCompareFn = {};
  19262. this._renderinGroupInfo = null;
  19263. this._scene = scene;
  19264. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19265. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19266. }
  19267. }
  19268. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19269. if (depth === void 0) { depth = true; }
  19270. if (stencil === void 0) { stencil = true; }
  19271. if (this._depthStencilBufferAlreadyCleaned) {
  19272. return;
  19273. }
  19274. this._scene.getEngine().clear(null, false, depth, stencil);
  19275. this._depthStencilBufferAlreadyCleaned = true;
  19276. };
  19277. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19278. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19279. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19280. var info = null;
  19281. if (observable) {
  19282. if (!this._renderinGroupInfo) {
  19283. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19284. }
  19285. info = this._renderinGroupInfo;
  19286. info.scene = this._scene;
  19287. info.camera = this._scene.activeCamera;
  19288. }
  19289. // Dispatch sprites
  19290. if (renderSprites) {
  19291. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19292. var manager = this._scene.spriteManagers[index];
  19293. this.dispatchSprites(manager);
  19294. }
  19295. }
  19296. // Render
  19297. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19298. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19299. var renderingGroup = this._renderingGroups[index];
  19300. if (!renderingGroup && !observable)
  19301. continue;
  19302. var renderingGroupMask = 0;
  19303. // Fire PRECLEAR stage
  19304. if (observable && info) {
  19305. renderingGroupMask = Math.pow(2, index);
  19306. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19307. info.renderingGroupId = index;
  19308. observable.notifyObservers(info, renderingGroupMask);
  19309. }
  19310. // Clear depth/stencil if needed
  19311. if (RenderingManager.AUTOCLEAR) {
  19312. var autoClear = this._autoClearDepthStencil[index];
  19313. if (autoClear && autoClear.autoClear) {
  19314. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19315. }
  19316. }
  19317. if (observable && info) {
  19318. // Fire PREOPAQUE stage
  19319. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19320. observable.notifyObservers(info, renderingGroupMask);
  19321. // Fire PRETRANSPARENT stage
  19322. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19323. observable.notifyObservers(info, renderingGroupMask);
  19324. }
  19325. if (renderingGroup)
  19326. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19327. // Fire POSTTRANSPARENT stage
  19328. if (observable && info) {
  19329. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19330. observable.notifyObservers(info, renderingGroupMask);
  19331. }
  19332. }
  19333. };
  19334. RenderingManager.prototype.reset = function () {
  19335. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19336. var renderingGroup = this._renderingGroups[index];
  19337. if (renderingGroup) {
  19338. renderingGroup.prepare();
  19339. }
  19340. }
  19341. };
  19342. RenderingManager.prototype.dispose = function () {
  19343. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19344. var renderingGroup = this._renderingGroups[index];
  19345. if (renderingGroup) {
  19346. renderingGroup.dispose();
  19347. }
  19348. }
  19349. this._renderingGroups.length = 0;
  19350. };
  19351. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19352. if (this._renderingGroups[renderingGroupId] === undefined) {
  19353. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19354. }
  19355. };
  19356. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19357. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19358. this._prepareRenderingGroup(renderingGroupId);
  19359. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19360. };
  19361. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19362. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19363. this._prepareRenderingGroup(renderingGroupId);
  19364. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19365. };
  19366. /**
  19367. * @param subMesh The submesh to dispatch
  19368. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19369. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19370. */
  19371. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19372. if (mesh === undefined) {
  19373. mesh = subMesh.getMesh();
  19374. }
  19375. var renderingGroupId = mesh.renderingGroupId || 0;
  19376. this._prepareRenderingGroup(renderingGroupId);
  19377. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19378. };
  19379. /**
  19380. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19381. * This allowed control for front to back rendering or reversly depending of the special needs.
  19382. *
  19383. * @param renderingGroupId The rendering group id corresponding to its index
  19384. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19385. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19386. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19387. */
  19388. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19389. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19390. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19391. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19392. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19393. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19394. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19395. if (this._renderingGroups[renderingGroupId]) {
  19396. var group = this._renderingGroups[renderingGroupId];
  19397. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19398. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19399. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19400. }
  19401. };
  19402. /**
  19403. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19404. *
  19405. * @param renderingGroupId The rendering group id corresponding to its index
  19406. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19407. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19408. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19409. */
  19410. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19411. if (depth === void 0) { depth = true; }
  19412. if (stencil === void 0) { stencil = true; }
  19413. this._autoClearDepthStencil[renderingGroupId] = {
  19414. autoClear: autoClearDepthStencil,
  19415. depth: depth,
  19416. stencil: stencil
  19417. };
  19418. };
  19419. /**
  19420. * The max id used for rendering groups (not included)
  19421. */
  19422. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19423. /**
  19424. * The min id used for rendering groups (included)
  19425. */
  19426. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19427. /**
  19428. * Used to globally prevent autoclearing scenes.
  19429. */
  19430. RenderingManager.AUTOCLEAR = true;
  19431. return RenderingManager;
  19432. }());
  19433. BABYLON.RenderingManager = RenderingManager;
  19434. })(BABYLON || (BABYLON = {}));
  19435. //# sourceMappingURL=babylon.renderingManager.js.map
  19436. var BABYLON;
  19437. (function (BABYLON) {
  19438. var RenderingGroup = /** @class */ (function () {
  19439. /**
  19440. * Creates a new rendering group.
  19441. * @param index The rendering group index
  19442. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19443. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19444. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19445. */
  19446. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19447. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19448. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19449. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19450. this.index = index;
  19451. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19452. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19453. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19454. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19455. this._particleSystems = new BABYLON.SmartArray(256);
  19456. this._spriteManagers = new BABYLON.SmartArray(256);
  19457. this._edgesRenderers = new BABYLON.SmartArray(16);
  19458. this._scene = scene;
  19459. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19460. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19461. this.transparentSortCompareFn = transparentSortCompareFn;
  19462. }
  19463. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19464. /**
  19465. * Set the opaque sort comparison function.
  19466. * If null the sub meshes will be render in the order they were created
  19467. */
  19468. set: function (value) {
  19469. this._opaqueSortCompareFn = value;
  19470. if (value) {
  19471. this._renderOpaque = this.renderOpaqueSorted;
  19472. }
  19473. else {
  19474. this._renderOpaque = RenderingGroup.renderUnsorted;
  19475. }
  19476. },
  19477. enumerable: true,
  19478. configurable: true
  19479. });
  19480. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19481. /**
  19482. * Set the alpha test sort comparison function.
  19483. * If null the sub meshes will be render in the order they were created
  19484. */
  19485. set: function (value) {
  19486. this._alphaTestSortCompareFn = value;
  19487. if (value) {
  19488. this._renderAlphaTest = this.renderAlphaTestSorted;
  19489. }
  19490. else {
  19491. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19492. }
  19493. },
  19494. enumerable: true,
  19495. configurable: true
  19496. });
  19497. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19498. /**
  19499. * Set the transparent sort comparison function.
  19500. * If null the sub meshes will be render in the order they were created
  19501. */
  19502. set: function (value) {
  19503. if (value) {
  19504. this._transparentSortCompareFn = value;
  19505. }
  19506. else {
  19507. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19508. }
  19509. this._renderTransparent = this.renderTransparentSorted;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. /**
  19515. * Render all the sub meshes contained in the group.
  19516. * @param customRenderFunction Used to override the default render behaviour of the group.
  19517. * @returns true if rendered some submeshes.
  19518. */
  19519. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19520. if (customRenderFunction) {
  19521. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19522. return;
  19523. }
  19524. var engine = this._scene.getEngine();
  19525. // Depth only
  19526. if (this._depthOnlySubMeshes.length !== 0) {
  19527. engine.setColorWrite(false);
  19528. this._renderAlphaTest(this._depthOnlySubMeshes);
  19529. engine.setColorWrite(true);
  19530. }
  19531. // Opaque
  19532. if (this._opaqueSubMeshes.length !== 0) {
  19533. this._renderOpaque(this._opaqueSubMeshes);
  19534. }
  19535. // Alpha test
  19536. if (this._alphaTestSubMeshes.length !== 0) {
  19537. this._renderAlphaTest(this._alphaTestSubMeshes);
  19538. }
  19539. var stencilState = engine.getStencilBuffer();
  19540. engine.setStencilBuffer(false);
  19541. // Sprites
  19542. if (renderSprites) {
  19543. this._renderSprites();
  19544. }
  19545. // Particles
  19546. if (renderParticles) {
  19547. this._renderParticles(activeMeshes);
  19548. }
  19549. if (this.onBeforeTransparentRendering) {
  19550. this.onBeforeTransparentRendering();
  19551. }
  19552. // Transparent
  19553. if (this._transparentSubMeshes.length !== 0) {
  19554. this._renderTransparent(this._transparentSubMeshes);
  19555. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19556. }
  19557. // Set back stencil to false in case it changes before the edge renderer.
  19558. engine.setStencilBuffer(false);
  19559. // Edges
  19560. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19561. this._edgesRenderers.data[edgesRendererIndex].render();
  19562. }
  19563. // Restore Stencil state.
  19564. engine.setStencilBuffer(stencilState);
  19565. };
  19566. /**
  19567. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19568. * @param subMeshes The submeshes to render
  19569. */
  19570. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19571. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19572. };
  19573. /**
  19574. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19575. * @param subMeshes The submeshes to render
  19576. */
  19577. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19578. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19579. };
  19580. /**
  19581. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19582. * @param subMeshes The submeshes to render
  19583. */
  19584. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19585. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19586. };
  19587. /**
  19588. * Renders the submeshes in a specified order.
  19589. * @param subMeshes The submeshes to sort before render
  19590. * @param sortCompareFn The comparison function use to sort
  19591. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19592. * @param transparent Specifies to activate blending if true
  19593. */
  19594. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19595. var subIndex = 0;
  19596. var subMesh;
  19597. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19598. for (; subIndex < subMeshes.length; subIndex++) {
  19599. subMesh = subMeshes.data[subIndex];
  19600. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19601. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19602. }
  19603. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19604. if (sortCompareFn) {
  19605. sortedArray.sort(sortCompareFn);
  19606. }
  19607. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19608. subMesh = sortedArray[subIndex];
  19609. if (transparent) {
  19610. var material = subMesh.getMaterial();
  19611. if (material && material.needDepthPrePass) {
  19612. var engine = material.getScene().getEngine();
  19613. engine.setColorWrite(false);
  19614. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19615. subMesh.render(false);
  19616. engine.setColorWrite(true);
  19617. }
  19618. }
  19619. subMesh.render(transparent);
  19620. }
  19621. };
  19622. /**
  19623. * Renders the submeshes in the order they were dispatched (no sort applied).
  19624. * @param subMeshes The submeshes to render
  19625. */
  19626. RenderingGroup.renderUnsorted = function (subMeshes) {
  19627. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19628. var submesh = subMeshes.data[subIndex];
  19629. submesh.render(false);
  19630. }
  19631. };
  19632. /**
  19633. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19634. * are rendered back to front if in the same alpha index.
  19635. *
  19636. * @param a The first submesh
  19637. * @param b The second submesh
  19638. * @returns The result of the comparison
  19639. */
  19640. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19641. // Alpha index first
  19642. if (a._alphaIndex > b._alphaIndex) {
  19643. return 1;
  19644. }
  19645. if (a._alphaIndex < b._alphaIndex) {
  19646. return -1;
  19647. }
  19648. // Then distance to camera
  19649. return RenderingGroup.backToFrontSortCompare(a, b);
  19650. };
  19651. /**
  19652. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19653. * are rendered back to front.
  19654. *
  19655. * @param a The first submesh
  19656. * @param b The second submesh
  19657. * @returns The result of the comparison
  19658. */
  19659. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19660. // Then distance to camera
  19661. if (a._distanceToCamera < b._distanceToCamera) {
  19662. return 1;
  19663. }
  19664. if (a._distanceToCamera > b._distanceToCamera) {
  19665. return -1;
  19666. }
  19667. return 0;
  19668. };
  19669. /**
  19670. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19671. * are rendered front to back (prevent overdraw).
  19672. *
  19673. * @param a The first submesh
  19674. * @param b The second submesh
  19675. * @returns The result of the comparison
  19676. */
  19677. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19678. // Then distance to camera
  19679. if (a._distanceToCamera < b._distanceToCamera) {
  19680. return -1;
  19681. }
  19682. if (a._distanceToCamera > b._distanceToCamera) {
  19683. return 1;
  19684. }
  19685. return 0;
  19686. };
  19687. /**
  19688. * Resets the different lists of submeshes to prepare a new frame.
  19689. */
  19690. RenderingGroup.prototype.prepare = function () {
  19691. this._opaqueSubMeshes.reset();
  19692. this._transparentSubMeshes.reset();
  19693. this._alphaTestSubMeshes.reset();
  19694. this._depthOnlySubMeshes.reset();
  19695. this._particleSystems.reset();
  19696. this._spriteManagers.reset();
  19697. this._edgesRenderers.reset();
  19698. };
  19699. RenderingGroup.prototype.dispose = function () {
  19700. this._opaqueSubMeshes.dispose();
  19701. this._transparentSubMeshes.dispose();
  19702. this._alphaTestSubMeshes.dispose();
  19703. this._depthOnlySubMeshes.dispose();
  19704. this._particleSystems.dispose();
  19705. this._spriteManagers.dispose();
  19706. this._edgesRenderers.dispose();
  19707. };
  19708. /**
  19709. * Inserts the submesh in its correct queue depending on its material.
  19710. * @param subMesh The submesh to dispatch
  19711. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19712. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19713. */
  19714. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19715. // Get mesh and materials if not provided
  19716. if (mesh === undefined) {
  19717. mesh = subMesh.getMesh();
  19718. }
  19719. if (material === undefined) {
  19720. material = subMesh.getMaterial();
  19721. }
  19722. if (material === null || material === undefined) {
  19723. return;
  19724. }
  19725. if (material.needAlphaBlendingForMesh(mesh)) {
  19726. this._transparentSubMeshes.push(subMesh);
  19727. }
  19728. else if (material.needAlphaTesting()) {
  19729. if (material.needDepthPrePass) {
  19730. this._depthOnlySubMeshes.push(subMesh);
  19731. }
  19732. this._alphaTestSubMeshes.push(subMesh);
  19733. }
  19734. else {
  19735. if (material.needDepthPrePass) {
  19736. this._depthOnlySubMeshes.push(subMesh);
  19737. }
  19738. this._opaqueSubMeshes.push(subMesh); // Opaque
  19739. }
  19740. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19741. this._edgesRenderers.push(mesh._edgesRenderer);
  19742. }
  19743. };
  19744. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19745. this._spriteManagers.push(spriteManager);
  19746. };
  19747. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19748. this._particleSystems.push(particleSystem);
  19749. };
  19750. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19751. if (this._particleSystems.length === 0) {
  19752. return;
  19753. }
  19754. // Particles
  19755. var activeCamera = this._scene.activeCamera;
  19756. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19757. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19758. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19759. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19760. continue;
  19761. }
  19762. var emitter = particleSystem.emitter;
  19763. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19764. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19765. }
  19766. }
  19767. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19768. };
  19769. RenderingGroup.prototype._renderSprites = function () {
  19770. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19771. return;
  19772. }
  19773. // Sprites
  19774. var activeCamera = this._scene.activeCamera;
  19775. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19776. for (var id = 0; id < this._spriteManagers.length; id++) {
  19777. var spriteManager = this._spriteManagers.data[id];
  19778. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19779. spriteManager.render();
  19780. }
  19781. }
  19782. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19783. };
  19784. return RenderingGroup;
  19785. }());
  19786. BABYLON.RenderingGroup = RenderingGroup;
  19787. })(BABYLON || (BABYLON = {}));
  19788. //# sourceMappingURL=babylon.renderingGroup.js.map
  19789. var BABYLON;
  19790. (function (BABYLON) {
  19791. var ClickInfo = /** @class */ (function () {
  19792. function ClickInfo() {
  19793. this._singleClick = false;
  19794. this._doubleClick = false;
  19795. this._hasSwiped = false;
  19796. this._ignore = false;
  19797. }
  19798. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19799. get: function () {
  19800. return this._singleClick;
  19801. },
  19802. set: function (b) {
  19803. this._singleClick = b;
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19809. get: function () {
  19810. return this._doubleClick;
  19811. },
  19812. set: function (b) {
  19813. this._doubleClick = b;
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19819. get: function () {
  19820. return this._hasSwiped;
  19821. },
  19822. set: function (b) {
  19823. this._hasSwiped = b;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19829. get: function () {
  19830. return this._ignore;
  19831. },
  19832. set: function (b) {
  19833. this._ignore = b;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. return ClickInfo;
  19839. }());
  19840. /**
  19841. * This class is used by the onRenderingGroupObservable
  19842. */
  19843. var RenderingGroupInfo = /** @class */ (function () {
  19844. function RenderingGroupInfo() {
  19845. }
  19846. /**
  19847. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19848. * This stage will be fired no matter what
  19849. */
  19850. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19851. /**
  19852. * Called before opaque object are rendered.
  19853. * This stage will be fired only if there's 3D Opaque content to render
  19854. */
  19855. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19856. /**
  19857. * Called after the opaque objects are rendered and before the transparent ones
  19858. * This stage will be fired only if there's 3D transparent content to render
  19859. */
  19860. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19861. /**
  19862. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19863. * This stage will be fired no matter what
  19864. */
  19865. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19866. return RenderingGroupInfo;
  19867. }());
  19868. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19869. /**
  19870. * Represents a scene to be rendered by the engine.
  19871. * @see http://doc.babylonjs.com/page.php?p=21911
  19872. */
  19873. var Scene = /** @class */ (function () {
  19874. /**
  19875. * @constructor
  19876. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19877. */
  19878. function Scene(engine) {
  19879. // Members
  19880. this.autoClear = true;
  19881. this.autoClearDepthAndStencil = true;
  19882. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19883. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19884. this.forceWireframe = false;
  19885. this._forcePointsCloud = false;
  19886. this.forceShowBoundingBoxes = false;
  19887. this.animationsEnabled = true;
  19888. this.useConstantAnimationDeltaTime = false;
  19889. this.constantlyUpdateMeshUnderPointer = false;
  19890. this.hoverCursor = "pointer";
  19891. this.defaultCursor = "";
  19892. /**
  19893. * This is used to call preventDefault() on pointer down
  19894. * in order to block unwanted artifacts like system double clicks
  19895. */
  19896. this.preventDefaultOnPointerDown = true;
  19897. // Metadata
  19898. this.metadata = null;
  19899. /**
  19900. * An event triggered when the scene is disposed.
  19901. * @type {BABYLON.Observable}
  19902. */
  19903. this.onDisposeObservable = new BABYLON.Observable();
  19904. /**
  19905. * An event triggered before rendering the scene (right after animations and physics)
  19906. * @type {BABYLON.Observable}
  19907. */
  19908. this.onBeforeRenderObservable = new BABYLON.Observable();
  19909. /**
  19910. * An event triggered after rendering the scene
  19911. * @type {BABYLON.Observable}
  19912. */
  19913. this.onAfterRenderObservable = new BABYLON.Observable();
  19914. /**
  19915. * An event triggered before animating the scene
  19916. * @type {BABYLON.Observable}
  19917. */
  19918. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19919. /**
  19920. * An event triggered after animations processing
  19921. * @type {BABYLON.Observable}
  19922. */
  19923. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19924. /**
  19925. * An event triggered before draw calls are ready to be sent
  19926. * @type {BABYLON.Observable}
  19927. */
  19928. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19929. /**
  19930. * An event triggered after draw calls have been sent
  19931. * @type {BABYLON.Observable}
  19932. */
  19933. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19934. /**
  19935. * An event triggered when physic simulation is about to be run
  19936. * @type {BABYLON.Observable}
  19937. */
  19938. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19939. /**
  19940. * An event triggered when physic simulation has been done
  19941. * @type {BABYLON.Observable}
  19942. */
  19943. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19944. /**
  19945. * An event triggered when the scene is ready
  19946. * @type {BABYLON.Observable}
  19947. */
  19948. this.onReadyObservable = new BABYLON.Observable();
  19949. /**
  19950. * An event triggered before rendering a camera
  19951. * @type {BABYLON.Observable}
  19952. */
  19953. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19954. /**
  19955. * An event triggered after rendering a camera
  19956. * @type {BABYLON.Observable}
  19957. */
  19958. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19959. /**
  19960. * An event triggered when active meshes evaluation is about to start
  19961. * @type {BABYLON.Observable}
  19962. */
  19963. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19964. /**
  19965. * An event triggered when active meshes evaluation is done
  19966. * @type {BABYLON.Observable}
  19967. */
  19968. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19969. /**
  19970. * An event triggered when particles rendering is about to start
  19971. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19972. * @type {BABYLON.Observable}
  19973. */
  19974. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19975. /**
  19976. * An event triggered when particles rendering is done
  19977. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19978. * @type {BABYLON.Observable}
  19979. */
  19980. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19981. /**
  19982. * An event triggered when sprites rendering is about to start
  19983. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19984. * @type {BABYLON.Observable}
  19985. */
  19986. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19987. /**
  19988. * An event triggered when sprites rendering is done
  19989. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19990. * @type {BABYLON.Observable}
  19991. */
  19992. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19993. /**
  19994. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19995. * @type {BABYLON.Observable}
  19996. */
  19997. this.onDataLoadedObservable = new BABYLON.Observable();
  19998. /**
  19999. * An event triggered when a camera is created
  20000. * @type {BABYLON.Observable}
  20001. */
  20002. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20003. /**
  20004. * An event triggered when a camera is removed
  20005. * @type {BABYLON.Observable}
  20006. */
  20007. this.onCameraRemovedObservable = new BABYLON.Observable();
  20008. /**
  20009. * An event triggered when a light is created
  20010. * @type {BABYLON.Observable}
  20011. */
  20012. this.onNewLightAddedObservable = new BABYLON.Observable();
  20013. /**
  20014. * An event triggered when a light is removed
  20015. * @type {BABYLON.Observable}
  20016. */
  20017. this.onLightRemovedObservable = new BABYLON.Observable();
  20018. /**
  20019. * An event triggered when a geometry is created
  20020. * @type {BABYLON.Observable}
  20021. */
  20022. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20023. /**
  20024. * An event triggered when a geometry is removed
  20025. * @type {BABYLON.Observable}
  20026. */
  20027. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20028. /**
  20029. * An event triggered when a transform node is created
  20030. * @type {BABYLON.Observable}
  20031. */
  20032. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20033. /**
  20034. * An event triggered when a transform node is removed
  20035. * @type {BABYLON.Observable}
  20036. */
  20037. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20038. /**
  20039. * An event triggered when a mesh is created
  20040. * @type {BABYLON.Observable}
  20041. */
  20042. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20043. /**
  20044. * An event triggered when a mesh is removed
  20045. * @type {BABYLON.Observable}
  20046. */
  20047. this.onMeshRemovedObservable = new BABYLON.Observable();
  20048. /**
  20049. * An event triggered when render targets are about to be rendered
  20050. * Can happen multiple times per frame.
  20051. * @type {BABYLON.Observable}
  20052. */
  20053. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20054. /**
  20055. * An event triggered when render targets were rendered.
  20056. * Can happen multiple times per frame.
  20057. * @type {BABYLON.Observable}
  20058. */
  20059. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20060. /**
  20061. * An event triggered before calculating deterministic simulation step
  20062. * @type {BABYLON.Observable}
  20063. */
  20064. this.onBeforeStepObservable = new BABYLON.Observable();
  20065. /**
  20066. * An event triggered after calculating deterministic simulation step
  20067. * @type {BABYLON.Observable}
  20068. */
  20069. this.onAfterStepObservable = new BABYLON.Observable();
  20070. /**
  20071. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20072. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20073. * 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)
  20074. */
  20075. this.onRenderingGroupObservable = new BABYLON.Observable();
  20076. // Animations
  20077. this.animations = [];
  20078. /**
  20079. * 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).
  20080. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20081. */
  20082. this.onPrePointerObservable = new BABYLON.Observable();
  20083. /**
  20084. * Observable event triggered each time an input event is received from the rendering canvas
  20085. */
  20086. this.onPointerObservable = new BABYLON.Observable();
  20087. this._meshPickProceed = false;
  20088. this._currentPickResult = null;
  20089. this._previousPickResult = null;
  20090. this._totalPointersPressed = 0;
  20091. this._doubleClickOccured = false;
  20092. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20093. this.cameraToUseForPointers = null;
  20094. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20095. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20096. this._startingPointerTime = 0;
  20097. this._previousStartingPointerTime = 0;
  20098. // Deterministic lockstep
  20099. this._timeAccumulator = 0;
  20100. this._currentStepId = 0;
  20101. this._currentInternalStep = 0;
  20102. // Keyboard
  20103. /**
  20104. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20105. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20106. */
  20107. this.onPreKeyboardObservable = new BABYLON.Observable();
  20108. /**
  20109. * Observable event triggered each time an keyboard event is received from the hosting window
  20110. */
  20111. this.onKeyboardObservable = new BABYLON.Observable();
  20112. // Coordinate system
  20113. /**
  20114. * use right-handed coordinate system on this scene.
  20115. * @type {boolean}
  20116. */
  20117. this._useRightHandedSystem = false;
  20118. // Fog
  20119. this._fogEnabled = true;
  20120. this._fogMode = Scene.FOGMODE_NONE;
  20121. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20122. this.fogDensity = 0.1;
  20123. this.fogStart = 0;
  20124. this.fogEnd = 1000.0;
  20125. // Lights
  20126. /**
  20127. * is shadow enabled on this scene.
  20128. * @type {boolean}
  20129. */
  20130. this._shadowsEnabled = true;
  20131. /**
  20132. * is light enabled on this scene.
  20133. * @type {boolean}
  20134. */
  20135. this._lightsEnabled = true;
  20136. /**
  20137. * All of the lights added to this scene.
  20138. * @see BABYLON.Light
  20139. * @type {BABYLON.Light[]}
  20140. */
  20141. this.lights = new Array();
  20142. // Cameras
  20143. /** All of the cameras added to this scene. */
  20144. this.cameras = new Array();
  20145. /** All of the active cameras added to this scene. */
  20146. this.activeCameras = new Array();
  20147. // Meshes
  20148. /**
  20149. * All of the tranform nodes added to this scene.
  20150. * @see BABYLON.TransformNode
  20151. * @type {BABYLON.TransformNode[]}
  20152. */
  20153. this.transformNodes = new Array();
  20154. /**
  20155. * All of the (abstract) meshes added to this scene.
  20156. * @see BABYLON.AbstractMesh
  20157. * @type {BABYLON.AbstractMesh[]}
  20158. */
  20159. this.meshes = new Array();
  20160. /**
  20161. * All of the animation groups added to this scene.
  20162. * @see BABYLON.AnimationGroup
  20163. * @type {BABYLON.AnimationGroup[]}
  20164. */
  20165. this.animationGroups = new Array();
  20166. // Geometries
  20167. this._geometries = new Array();
  20168. this.materials = new Array();
  20169. this.multiMaterials = new Array();
  20170. // Textures
  20171. this._texturesEnabled = true;
  20172. this.textures = new Array();
  20173. // Particles
  20174. this.particlesEnabled = true;
  20175. this.particleSystems = new Array();
  20176. // Sprites
  20177. this.spritesEnabled = true;
  20178. this.spriteManagers = new Array();
  20179. // Layers
  20180. this.layers = new Array();
  20181. this.highlightLayers = new Array();
  20182. // Skeletons
  20183. this._skeletonsEnabled = true;
  20184. this.skeletons = new Array();
  20185. // Morph targets
  20186. this.morphTargetManagers = new Array();
  20187. // Lens flares
  20188. this.lensFlaresEnabled = true;
  20189. this.lensFlareSystems = new Array();
  20190. // Collisions
  20191. this.collisionsEnabled = true;
  20192. /** Defines the gravity applied to this scene */
  20193. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20194. // Postprocesses
  20195. this.postProcesses = new Array();
  20196. this.postProcessesEnabled = true;
  20197. // Customs render targets
  20198. this.renderTargetsEnabled = true;
  20199. this.dumpNextRenderTargets = false;
  20200. this.customRenderTargets = new Array();
  20201. // Imported meshes
  20202. this.importedMeshesFiles = new Array();
  20203. // Probes
  20204. this.probesEnabled = true;
  20205. this.reflectionProbes = new Array();
  20206. this._actionManagers = new Array();
  20207. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20208. // Procedural textures
  20209. this.proceduralTexturesEnabled = true;
  20210. this._proceduralTextures = new Array();
  20211. this.soundTracks = new Array();
  20212. this._audioEnabled = true;
  20213. this._headphone = false;
  20214. // Performance counters
  20215. this._totalVertices = new BABYLON.PerfCounter();
  20216. this._activeIndices = new BABYLON.PerfCounter();
  20217. this._activeParticles = new BABYLON.PerfCounter();
  20218. this._activeBones = new BABYLON.PerfCounter();
  20219. this._animationTime = 0;
  20220. this.animationTimeScale = 1;
  20221. this._renderId = 0;
  20222. this._executeWhenReadyTimeoutId = -1;
  20223. this._intermediateRendering = false;
  20224. this._viewUpdateFlag = -1;
  20225. this._projectionUpdateFlag = -1;
  20226. this._alternateViewUpdateFlag = -1;
  20227. this._alternateProjectionUpdateFlag = -1;
  20228. this._toBeDisposed = new BABYLON.SmartArray(256);
  20229. this._activeRequests = new Array();
  20230. this._pendingData = new Array();
  20231. this._isDisposed = false;
  20232. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20233. this._activeMeshes = new BABYLON.SmartArray(256);
  20234. this._processedMaterials = new BABYLON.SmartArray(256);
  20235. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20236. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20237. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20238. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20239. this._activeAnimatables = new Array();
  20240. this._transformMatrix = BABYLON.Matrix.Zero();
  20241. this._useAlternateCameraConfiguration = false;
  20242. this._alternateRendering = false;
  20243. this.requireLightSorting = false;
  20244. this._activeMeshesFrozen = false;
  20245. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20246. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20247. this._engine.scenes.push(this);
  20248. this._uid = null;
  20249. this._renderingManager = new BABYLON.RenderingManager(this);
  20250. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20251. if (BABYLON.OutlineRenderer) {
  20252. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20253. }
  20254. if (BABYLON.Tools.IsWindowObjectExist()) {
  20255. this.attachControl();
  20256. }
  20257. //simplification queue
  20258. if (BABYLON.SimplificationQueue) {
  20259. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20260. }
  20261. //collision coordinator initialization. For now legacy per default.
  20262. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20263. // Uniform Buffer
  20264. this._createUbo();
  20265. // Default Image processing definition.
  20266. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20267. }
  20268. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20269. /** The fog is deactivated */
  20270. get: function () {
  20271. return Scene._FOGMODE_NONE;
  20272. },
  20273. enumerable: true,
  20274. configurable: true
  20275. });
  20276. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20277. /** The fog density is following an exponential function */
  20278. get: function () {
  20279. return Scene._FOGMODE_EXP;
  20280. },
  20281. enumerable: true,
  20282. configurable: true
  20283. });
  20284. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20285. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20286. get: function () {
  20287. return Scene._FOGMODE_EXP2;
  20288. },
  20289. enumerable: true,
  20290. configurable: true
  20291. });
  20292. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20293. /** The fog density is following a linear function. */
  20294. get: function () {
  20295. return Scene._FOGMODE_LINEAR;
  20296. },
  20297. enumerable: true,
  20298. configurable: true
  20299. });
  20300. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20301. /**
  20302. * Texture used in all pbr material as the reflection texture.
  20303. * As in the majority of the scene they are the same (exception for multi room and so on),
  20304. * this is easier to reference from here than from all the materials.
  20305. */
  20306. get: function () {
  20307. return this._environmentTexture;
  20308. },
  20309. /**
  20310. * Texture used in all pbr material as the reflection texture.
  20311. * As in the majority of the scene they are the same (exception for multi room and so on),
  20312. * this is easier to set here than in all the materials.
  20313. */
  20314. set: function (value) {
  20315. if (this._environmentTexture === value) {
  20316. return;
  20317. }
  20318. this._environmentTexture = value;
  20319. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20320. },
  20321. enumerable: true,
  20322. configurable: true
  20323. });
  20324. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  20325. /**
  20326. * Default image processing configuration used either in the rendering
  20327. * Forward main pass or through the imageProcessingPostProcess if present.
  20328. * As in the majority of the scene they are the same (exception for multi camera),
  20329. * this is easier to reference from here than from all the materials and post process.
  20330. *
  20331. * No setter as we it is a shared configuration, you can set the values instead.
  20332. */
  20333. get: function () {
  20334. return this._imageProcessingConfiguration;
  20335. },
  20336. enumerable: true,
  20337. configurable: true
  20338. });
  20339. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20340. get: function () {
  20341. return this._forcePointsCloud;
  20342. },
  20343. set: function (value) {
  20344. if (this._forcePointsCloud === value) {
  20345. return;
  20346. }
  20347. this._forcePointsCloud = value;
  20348. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20349. },
  20350. enumerable: true,
  20351. configurable: true
  20352. });
  20353. Object.defineProperty(Scene.prototype, "onDispose", {
  20354. /** A function to be executed when this scene is disposed. */
  20355. set: function (callback) {
  20356. if (this._onDisposeObserver) {
  20357. this.onDisposeObservable.remove(this._onDisposeObserver);
  20358. }
  20359. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20360. },
  20361. enumerable: true,
  20362. configurable: true
  20363. });
  20364. Object.defineProperty(Scene.prototype, "beforeRender", {
  20365. /** A function to be executed before rendering this scene */
  20366. set: function (callback) {
  20367. if (this._onBeforeRenderObserver) {
  20368. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20369. }
  20370. if (callback) {
  20371. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20372. }
  20373. },
  20374. enumerable: true,
  20375. configurable: true
  20376. });
  20377. Object.defineProperty(Scene.prototype, "afterRender", {
  20378. /** A function to be executed after rendering this scene */
  20379. set: function (callback) {
  20380. if (this._onAfterRenderObserver) {
  20381. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20382. }
  20383. if (callback) {
  20384. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20385. }
  20386. },
  20387. enumerable: true,
  20388. configurable: true
  20389. });
  20390. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20391. set: function (callback) {
  20392. if (this._onBeforeCameraRenderObserver) {
  20393. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20394. }
  20395. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20396. },
  20397. enumerable: true,
  20398. configurable: true
  20399. });
  20400. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20401. set: function (callback) {
  20402. if (this._onAfterCameraRenderObserver) {
  20403. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20404. }
  20405. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20406. },
  20407. enumerable: true,
  20408. configurable: true
  20409. });
  20410. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20411. get: function () {
  20412. if (!this._gamepadManager) {
  20413. this._gamepadManager = new BABYLON.GamepadManager(this);
  20414. }
  20415. return this._gamepadManager;
  20416. },
  20417. enumerable: true,
  20418. configurable: true
  20419. });
  20420. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20421. get: function () {
  20422. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20423. },
  20424. enumerable: true,
  20425. configurable: true
  20426. });
  20427. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20428. get: function () {
  20429. return this._useRightHandedSystem;
  20430. },
  20431. set: function (value) {
  20432. if (this._useRightHandedSystem === value) {
  20433. return;
  20434. }
  20435. this._useRightHandedSystem = value;
  20436. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20437. },
  20438. enumerable: true,
  20439. configurable: true
  20440. });
  20441. Scene.prototype.setStepId = function (newStepId) {
  20442. this._currentStepId = newStepId;
  20443. };
  20444. ;
  20445. Scene.prototype.getStepId = function () {
  20446. return this._currentStepId;
  20447. };
  20448. ;
  20449. Scene.prototype.getInternalStep = function () {
  20450. return this._currentInternalStep;
  20451. };
  20452. ;
  20453. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20454. get: function () {
  20455. return this._fogEnabled;
  20456. },
  20457. /**
  20458. * is fog enabled on this scene.
  20459. */
  20460. set: function (value) {
  20461. if (this._fogEnabled === value) {
  20462. return;
  20463. }
  20464. this._fogEnabled = value;
  20465. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20466. },
  20467. enumerable: true,
  20468. configurable: true
  20469. });
  20470. Object.defineProperty(Scene.prototype, "fogMode", {
  20471. get: function () {
  20472. return this._fogMode;
  20473. },
  20474. set: function (value) {
  20475. if (this._fogMode === value) {
  20476. return;
  20477. }
  20478. this._fogMode = value;
  20479. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20480. },
  20481. enumerable: true,
  20482. configurable: true
  20483. });
  20484. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20485. get: function () {
  20486. return this._shadowsEnabled;
  20487. },
  20488. set: function (value) {
  20489. if (this._shadowsEnabled === value) {
  20490. return;
  20491. }
  20492. this._shadowsEnabled = value;
  20493. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20494. },
  20495. enumerable: true,
  20496. configurable: true
  20497. });
  20498. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20499. get: function () {
  20500. return this._lightsEnabled;
  20501. },
  20502. set: function (value) {
  20503. if (this._lightsEnabled === value) {
  20504. return;
  20505. }
  20506. this._lightsEnabled = value;
  20507. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20508. },
  20509. enumerable: true,
  20510. configurable: true
  20511. });
  20512. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20513. /** The default material used on meshes when no material is affected */
  20514. get: function () {
  20515. if (!this._defaultMaterial) {
  20516. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20517. }
  20518. return this._defaultMaterial;
  20519. },
  20520. /** The default material used on meshes when no material is affected */
  20521. set: function (value) {
  20522. this._defaultMaterial = value;
  20523. },
  20524. enumerable: true,
  20525. configurable: true
  20526. });
  20527. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20528. get: function () {
  20529. return this._texturesEnabled;
  20530. },
  20531. set: function (value) {
  20532. if (this._texturesEnabled === value) {
  20533. return;
  20534. }
  20535. this._texturesEnabled = value;
  20536. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20537. },
  20538. enumerable: true,
  20539. configurable: true
  20540. });
  20541. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20542. get: function () {
  20543. return this._skeletonsEnabled;
  20544. },
  20545. set: function (value) {
  20546. if (this._skeletonsEnabled === value) {
  20547. return;
  20548. }
  20549. this._skeletonsEnabled = value;
  20550. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20551. },
  20552. enumerable: true,
  20553. configurable: true
  20554. });
  20555. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20556. get: function () {
  20557. if (!this._postProcessRenderPipelineManager) {
  20558. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20559. }
  20560. return this._postProcessRenderPipelineManager;
  20561. },
  20562. enumerable: true,
  20563. configurable: true
  20564. });
  20565. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20566. get: function () {
  20567. if (!this._mainSoundTrack) {
  20568. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20569. }
  20570. return this._mainSoundTrack;
  20571. },
  20572. enumerable: true,
  20573. configurable: true
  20574. });
  20575. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20576. get: function () {
  20577. return this._alternateRendering;
  20578. },
  20579. enumerable: true,
  20580. configurable: true
  20581. });
  20582. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20583. get: function () {
  20584. return this._frustumPlanes;
  20585. },
  20586. enumerable: true,
  20587. configurable: true
  20588. });
  20589. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20590. /**
  20591. * Gets the current geometry buffer associated to the scene.
  20592. */
  20593. get: function () {
  20594. return this._geometryBufferRenderer;
  20595. },
  20596. /**
  20597. * Sets the current geometry buffer for the scene.
  20598. */
  20599. set: function (geometryBufferRenderer) {
  20600. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20601. this._geometryBufferRenderer = geometryBufferRenderer;
  20602. }
  20603. },
  20604. enumerable: true,
  20605. configurable: true
  20606. });
  20607. Object.defineProperty(Scene.prototype, "debugLayer", {
  20608. // Properties
  20609. get: function () {
  20610. if (!this._debugLayer) {
  20611. this._debugLayer = new BABYLON.DebugLayer(this);
  20612. }
  20613. return this._debugLayer;
  20614. },
  20615. enumerable: true,
  20616. configurable: true
  20617. });
  20618. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20619. get: function () {
  20620. return this._workerCollisions;
  20621. },
  20622. set: function (enabled) {
  20623. if (!BABYLON.CollisionCoordinatorLegacy) {
  20624. return;
  20625. }
  20626. enabled = (enabled && !!Worker);
  20627. this._workerCollisions = enabled;
  20628. if (this.collisionCoordinator) {
  20629. this.collisionCoordinator.destroy();
  20630. }
  20631. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20632. this.collisionCoordinator.init(this);
  20633. },
  20634. enumerable: true,
  20635. configurable: true
  20636. });
  20637. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20638. get: function () {
  20639. return this._selectionOctree;
  20640. },
  20641. enumerable: true,
  20642. configurable: true
  20643. });
  20644. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20645. /**
  20646. * The mesh that is currently under the pointer.
  20647. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20648. */
  20649. get: function () {
  20650. return this._pointerOverMesh;
  20651. },
  20652. enumerable: true,
  20653. configurable: true
  20654. });
  20655. Object.defineProperty(Scene.prototype, "pointerX", {
  20656. /**
  20657. * Current on-screen X position of the pointer
  20658. * @return {number} X position of the pointer
  20659. */
  20660. get: function () {
  20661. return this._pointerX;
  20662. },
  20663. enumerable: true,
  20664. configurable: true
  20665. });
  20666. Object.defineProperty(Scene.prototype, "pointerY", {
  20667. /**
  20668. * Current on-screen Y position of the pointer
  20669. * @return {number} Y position of the pointer
  20670. */
  20671. get: function () {
  20672. return this._pointerY;
  20673. },
  20674. enumerable: true,
  20675. configurable: true
  20676. });
  20677. Scene.prototype.getCachedMaterial = function () {
  20678. return this._cachedMaterial;
  20679. };
  20680. Scene.prototype.getCachedEffect = function () {
  20681. return this._cachedEffect;
  20682. };
  20683. Scene.prototype.getCachedVisibility = function () {
  20684. return this._cachedVisibility;
  20685. };
  20686. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20687. if (visibility === void 0) { visibility = 1; }
  20688. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20689. };
  20690. Scene.prototype.getBoundingBoxRenderer = function () {
  20691. if (!this._boundingBoxRenderer) {
  20692. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20693. }
  20694. return this._boundingBoxRenderer;
  20695. };
  20696. Scene.prototype.getOutlineRenderer = function () {
  20697. return this._outlineRenderer;
  20698. };
  20699. Scene.prototype.getEngine = function () {
  20700. return this._engine;
  20701. };
  20702. Scene.prototype.getTotalVertices = function () {
  20703. return this._totalVertices.current;
  20704. };
  20705. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20706. get: function () {
  20707. return this._totalVertices;
  20708. },
  20709. enumerable: true,
  20710. configurable: true
  20711. });
  20712. Scene.prototype.getActiveIndices = function () {
  20713. return this._activeIndices.current;
  20714. };
  20715. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20716. get: function () {
  20717. return this._activeIndices;
  20718. },
  20719. enumerable: true,
  20720. configurable: true
  20721. });
  20722. Scene.prototype.getActiveParticles = function () {
  20723. return this._activeParticles.current;
  20724. };
  20725. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20726. get: function () {
  20727. return this._activeParticles;
  20728. },
  20729. enumerable: true,
  20730. configurable: true
  20731. });
  20732. Scene.prototype.getActiveBones = function () {
  20733. return this._activeBones.current;
  20734. };
  20735. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20736. get: function () {
  20737. return this._activeBones;
  20738. },
  20739. enumerable: true,
  20740. configurable: true
  20741. });
  20742. // Stats
  20743. Scene.prototype.getInterFramePerfCounter = function () {
  20744. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20745. return 0;
  20746. };
  20747. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20748. get: function () {
  20749. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20750. return null;
  20751. },
  20752. enumerable: true,
  20753. configurable: true
  20754. });
  20755. Scene.prototype.getLastFrameDuration = function () {
  20756. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20757. return 0;
  20758. };
  20759. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20760. get: function () {
  20761. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20762. return null;
  20763. },
  20764. enumerable: true,
  20765. configurable: true
  20766. });
  20767. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20768. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20769. return 0;
  20770. };
  20771. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20772. get: function () {
  20773. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20774. return null;
  20775. },
  20776. enumerable: true,
  20777. configurable: true
  20778. });
  20779. Scene.prototype.getActiveMeshes = function () {
  20780. return this._activeMeshes;
  20781. };
  20782. Scene.prototype.getRenderTargetsDuration = function () {
  20783. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20784. return 0;
  20785. };
  20786. Scene.prototype.getRenderDuration = function () {
  20787. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20788. return 0;
  20789. };
  20790. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20791. get: function () {
  20792. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20793. return null;
  20794. },
  20795. enumerable: true,
  20796. configurable: true
  20797. });
  20798. Scene.prototype.getParticlesDuration = function () {
  20799. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20800. return 0;
  20801. };
  20802. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20803. get: function () {
  20804. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20805. return null;
  20806. },
  20807. enumerable: true,
  20808. configurable: true
  20809. });
  20810. Scene.prototype.getSpritesDuration = function () {
  20811. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20812. return 0;
  20813. };
  20814. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20815. get: function () {
  20816. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20817. return null;
  20818. },
  20819. enumerable: true,
  20820. configurable: true
  20821. });
  20822. Scene.prototype.getAnimationRatio = function () {
  20823. return this._animationRatio;
  20824. };
  20825. Scene.prototype.getRenderId = function () {
  20826. return this._renderId;
  20827. };
  20828. Scene.prototype.incrementRenderId = function () {
  20829. this._renderId++;
  20830. };
  20831. Scene.prototype._updatePointerPosition = function (evt) {
  20832. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20833. if (!canvasRect) {
  20834. return;
  20835. }
  20836. this._pointerX = evt.clientX - canvasRect.left;
  20837. this._pointerY = evt.clientY - canvasRect.top;
  20838. this._unTranslatedPointerX = this._pointerX;
  20839. this._unTranslatedPointerY = this._pointerY;
  20840. };
  20841. Scene.prototype._createUbo = function () {
  20842. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20843. this._sceneUbo.addUniform("viewProjection", 16);
  20844. this._sceneUbo.addUniform("view", 16);
  20845. };
  20846. Scene.prototype._createAlternateUbo = function () {
  20847. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20848. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20849. this._alternateSceneUbo.addUniform("view", 16);
  20850. };
  20851. // Pointers handling
  20852. /**
  20853. * Use this method to simulate a pointer move on a mesh
  20854. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20855. */
  20856. Scene.prototype.simulatePointerMove = function (pickResult) {
  20857. var evt = new PointerEvent("pointermove");
  20858. return this._processPointerMove(pickResult, evt);
  20859. };
  20860. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20861. var canvas = this._engine.getRenderingCanvas();
  20862. if (!canvas) {
  20863. return this;
  20864. }
  20865. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20866. this.setPointerOverSprite(null);
  20867. this.setPointerOverMesh(pickResult.pickedMesh);
  20868. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20869. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20870. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20871. }
  20872. else {
  20873. canvas.style.cursor = this.hoverCursor;
  20874. }
  20875. }
  20876. else {
  20877. canvas.style.cursor = this.defaultCursor;
  20878. }
  20879. }
  20880. else {
  20881. this.setPointerOverMesh(null);
  20882. // Sprites
  20883. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20884. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20885. this.setPointerOverSprite(pickResult.pickedSprite);
  20886. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20887. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20888. }
  20889. else {
  20890. canvas.style.cursor = this.hoverCursor;
  20891. }
  20892. }
  20893. else {
  20894. this.setPointerOverSprite(null);
  20895. // Restore pointer
  20896. canvas.style.cursor = this.defaultCursor;
  20897. }
  20898. }
  20899. if (pickResult) {
  20900. if (this.onPointerMove) {
  20901. this.onPointerMove(evt, pickResult);
  20902. }
  20903. if (this.onPointerObservable.hasObservers()) {
  20904. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20905. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20906. this.onPointerObservable.notifyObservers(pi, type);
  20907. }
  20908. }
  20909. return this;
  20910. };
  20911. /**
  20912. * Use this method to simulate a pointer down on a mesh
  20913. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20914. */
  20915. Scene.prototype.simulatePointerDown = function (pickResult) {
  20916. var evt = new PointerEvent("pointerdown");
  20917. return this._processPointerDown(pickResult, evt);
  20918. };
  20919. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20920. var _this = this;
  20921. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20922. this._pickedDownMesh = pickResult.pickedMesh;
  20923. var actionManager = pickResult.pickedMesh.actionManager;
  20924. if (actionManager) {
  20925. if (actionManager.hasPickTriggers) {
  20926. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20927. switch (evt.button) {
  20928. case 0:
  20929. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20930. break;
  20931. case 1:
  20932. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20933. break;
  20934. case 2:
  20935. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20936. break;
  20937. }
  20938. }
  20939. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20940. window.setTimeout(function () {
  20941. 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);
  20942. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20943. if (_this._totalPointersPressed !== 0 &&
  20944. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20945. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20946. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20947. _this._startingPointerTime = 0;
  20948. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20949. }
  20950. }
  20951. }, Scene.LongPressDelay);
  20952. }
  20953. }
  20954. }
  20955. if (pickResult) {
  20956. if (this.onPointerDown) {
  20957. this.onPointerDown(evt, pickResult);
  20958. }
  20959. if (this.onPointerObservable.hasObservers()) {
  20960. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20961. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20962. this.onPointerObservable.notifyObservers(pi, type);
  20963. }
  20964. }
  20965. return this;
  20966. };
  20967. /**
  20968. * Use this method to simulate a pointer up on a mesh
  20969. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20970. */
  20971. Scene.prototype.simulatePointerUp = function (pickResult) {
  20972. var evt = new PointerEvent("pointerup");
  20973. var clickInfo = new ClickInfo();
  20974. clickInfo.singleClick = true;
  20975. clickInfo.ignore = true;
  20976. return this._processPointerUp(pickResult, evt, clickInfo);
  20977. };
  20978. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20979. if (pickResult && pickResult && pickResult.pickedMesh) {
  20980. this._pickedUpMesh = pickResult.pickedMesh;
  20981. if (this._pickedDownMesh === this._pickedUpMesh) {
  20982. if (this.onPointerPick) {
  20983. this.onPointerPick(evt, pickResult);
  20984. }
  20985. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20986. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20987. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20988. this.onPointerObservable.notifyObservers(pi, type);
  20989. }
  20990. }
  20991. if (pickResult.pickedMesh.actionManager) {
  20992. if (clickInfo.ignore) {
  20993. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20994. }
  20995. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20996. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20997. }
  20998. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20999. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21000. }
  21001. }
  21002. }
  21003. if (this._pickedDownMesh &&
  21004. this._pickedDownMesh.actionManager &&
  21005. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21006. this._pickedDownMesh !== this._pickedUpMesh) {
  21007. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21008. }
  21009. if (this.onPointerUp) {
  21010. this.onPointerUp(evt, pickResult);
  21011. }
  21012. if (this.onPointerObservable.hasObservers()) {
  21013. if (!clickInfo.ignore) {
  21014. if (!clickInfo.hasSwiped) {
  21015. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21016. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21017. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21018. this.onPointerObservable.notifyObservers(pi, type);
  21019. }
  21020. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21021. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21022. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21023. this.onPointerObservable.notifyObservers(pi, type);
  21024. }
  21025. }
  21026. }
  21027. else {
  21028. var type = BABYLON.PointerEventTypes.POINTERUP;
  21029. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21030. this.onPointerObservable.notifyObservers(pi, type);
  21031. }
  21032. }
  21033. return this;
  21034. };
  21035. /**
  21036. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21037. * @param attachUp defines if you want to attach events to pointerup
  21038. * @param attachDown defines if you want to attach events to pointerdown
  21039. * @param attachMove defines if you want to attach events to pointermove
  21040. */
  21041. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21042. var _this = this;
  21043. if (attachUp === void 0) { attachUp = true; }
  21044. if (attachDown === void 0) { attachDown = true; }
  21045. if (attachMove === void 0) { attachMove = true; }
  21046. this._initActionManager = function (act, clickInfo) {
  21047. if (!_this._meshPickProceed) {
  21048. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21049. _this._currentPickResult = pickResult;
  21050. if (pickResult) {
  21051. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21052. }
  21053. _this._meshPickProceed = true;
  21054. }
  21055. return act;
  21056. };
  21057. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21058. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21059. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21060. btn !== _this._previousButtonPressed) {
  21061. _this._doubleClickOccured = false;
  21062. clickInfo.singleClick = true;
  21063. clickInfo.ignore = false;
  21064. cb(clickInfo, _this._currentPickResult);
  21065. }
  21066. };
  21067. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21068. var clickInfo = new ClickInfo();
  21069. _this._currentPickResult = null;
  21070. var act = null;
  21071. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21072. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21073. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21074. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21075. act = _this._initActionManager(act, clickInfo);
  21076. if (act)
  21077. checkPicking = act.hasPickTriggers;
  21078. }
  21079. if (checkPicking) {
  21080. var btn = evt.button;
  21081. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21082. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21083. if (!clickInfo.hasSwiped) {
  21084. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21085. if (!checkSingleClickImmediately) {
  21086. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21087. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21088. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21089. act = _this._initActionManager(act, clickInfo);
  21090. if (act)
  21091. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21092. }
  21093. }
  21094. if (checkSingleClickImmediately) {
  21095. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21096. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21097. btn !== _this._previousButtonPressed) {
  21098. clickInfo.singleClick = true;
  21099. cb(clickInfo, _this._currentPickResult);
  21100. }
  21101. }
  21102. else {
  21103. // wait that no double click has been raised during the double click delay
  21104. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21105. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21106. }
  21107. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21108. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21109. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21110. act = _this._initActionManager(act, clickInfo);
  21111. if (act)
  21112. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21113. }
  21114. if (checkDoubleClick) {
  21115. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21116. if (btn === _this._previousButtonPressed &&
  21117. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21118. !_this._doubleClickOccured) {
  21119. // pointer has not moved for 2 clicks, it's a double click
  21120. if (!clickInfo.hasSwiped &&
  21121. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21122. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21123. _this._previousStartingPointerTime = 0;
  21124. _this._doubleClickOccured = true;
  21125. clickInfo.doubleClick = true;
  21126. clickInfo.ignore = false;
  21127. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21128. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21129. }
  21130. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21131. cb(clickInfo, _this._currentPickResult);
  21132. }
  21133. else {
  21134. _this._doubleClickOccured = false;
  21135. _this._previousStartingPointerTime = _this._startingPointerTime;
  21136. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21137. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21138. _this._previousButtonPressed = btn;
  21139. if (Scene.ExclusiveDoubleClickMode) {
  21140. if (_this._previousDelayedSimpleClickTimeout) {
  21141. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21142. }
  21143. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21144. cb(clickInfo, _this._previousPickResult);
  21145. }
  21146. else {
  21147. cb(clickInfo, _this._currentPickResult);
  21148. }
  21149. }
  21150. }
  21151. else {
  21152. _this._doubleClickOccured = false;
  21153. _this._previousStartingPointerTime = _this._startingPointerTime;
  21154. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21155. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21156. _this._previousButtonPressed = btn;
  21157. }
  21158. }
  21159. }
  21160. }
  21161. clickInfo.ignore = true;
  21162. cb(clickInfo, _this._currentPickResult);
  21163. };
  21164. this._spritePredicate = function (sprite) {
  21165. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21166. };
  21167. this._onPointerMove = function (evt) {
  21168. _this._updatePointerPosition(evt);
  21169. // PreObservable support
  21170. if (_this.onPrePointerObservable.hasObservers()) {
  21171. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21172. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21173. _this.onPrePointerObservable.notifyObservers(pi, type);
  21174. if (pi.skipOnPointerObservable) {
  21175. return;
  21176. }
  21177. }
  21178. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21179. return;
  21180. }
  21181. if (!_this.pointerMovePredicate) {
  21182. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21183. }
  21184. // Meshes
  21185. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21186. _this._processPointerMove(pickResult, evt);
  21187. };
  21188. this._onPointerDown = function (evt) {
  21189. _this._totalPointersPressed++;
  21190. _this._pickedDownMesh = null;
  21191. _this._meshPickProceed = false;
  21192. _this._updatePointerPosition(evt);
  21193. if (_this.preventDefaultOnPointerDown && canvas) {
  21194. evt.preventDefault();
  21195. canvas.focus();
  21196. }
  21197. // PreObservable support
  21198. if (_this.onPrePointerObservable.hasObservers()) {
  21199. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21200. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21201. _this.onPrePointerObservable.notifyObservers(pi, type);
  21202. if (pi.skipOnPointerObservable) {
  21203. return;
  21204. }
  21205. }
  21206. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21207. return;
  21208. }
  21209. _this._startingPointerPosition.x = _this._pointerX;
  21210. _this._startingPointerPosition.y = _this._pointerY;
  21211. _this._startingPointerTime = new Date().getTime();
  21212. if (!_this.pointerDownPredicate) {
  21213. _this.pointerDownPredicate = function (mesh) {
  21214. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21215. };
  21216. }
  21217. // Meshes
  21218. _this._pickedDownMesh = null;
  21219. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21220. _this._processPointerDown(pickResult, evt);
  21221. // Sprites
  21222. _this._pickedDownSprite = null;
  21223. if (_this.spriteManagers.length > 0) {
  21224. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21225. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21226. if (pickResult.pickedSprite.actionManager) {
  21227. _this._pickedDownSprite = pickResult.pickedSprite;
  21228. switch (evt.button) {
  21229. case 0:
  21230. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21231. break;
  21232. case 1:
  21233. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21234. break;
  21235. case 2:
  21236. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21237. break;
  21238. }
  21239. if (pickResult.pickedSprite.actionManager) {
  21240. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21241. }
  21242. }
  21243. }
  21244. }
  21245. };
  21246. this._onPointerUp = function (evt) {
  21247. if (_this._totalPointersPressed === 0) {
  21248. return; // So we need to test it the pointer down was pressed before.
  21249. }
  21250. _this._totalPointersPressed--;
  21251. _this._pickedUpMesh = null;
  21252. _this._meshPickProceed = false;
  21253. _this._updatePointerPosition(evt);
  21254. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21255. // PreObservable support
  21256. if (_this.onPrePointerObservable.hasObservers()) {
  21257. if (!clickInfo.ignore) {
  21258. if (!clickInfo.hasSwiped) {
  21259. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21260. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21261. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21262. _this.onPrePointerObservable.notifyObservers(pi, type);
  21263. if (pi.skipOnPointerObservable) {
  21264. return;
  21265. }
  21266. }
  21267. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21268. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21269. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21270. _this.onPrePointerObservable.notifyObservers(pi, type);
  21271. if (pi.skipOnPointerObservable) {
  21272. return;
  21273. }
  21274. }
  21275. }
  21276. }
  21277. else {
  21278. var type = BABYLON.PointerEventTypes.POINTERUP;
  21279. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21280. _this.onPrePointerObservable.notifyObservers(pi, type);
  21281. if (pi.skipOnPointerObservable) {
  21282. return;
  21283. }
  21284. }
  21285. }
  21286. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21287. return;
  21288. }
  21289. if (!_this.pointerUpPredicate) {
  21290. _this.pointerUpPredicate = function (mesh) {
  21291. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21292. };
  21293. }
  21294. // Meshes
  21295. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21296. _this._initActionManager(null, clickInfo);
  21297. }
  21298. if (!pickResult) {
  21299. pickResult = _this._currentPickResult;
  21300. }
  21301. _this._processPointerUp(pickResult, evt, clickInfo);
  21302. // Sprites
  21303. if (_this.spriteManagers.length > 0) {
  21304. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21305. if (spritePickResult) {
  21306. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  21307. if (spritePickResult.pickedSprite.actionManager) {
  21308. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21309. if (spritePickResult.pickedSprite.actionManager) {
  21310. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  21311. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21312. }
  21313. }
  21314. }
  21315. }
  21316. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  21317. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  21318. }
  21319. }
  21320. }
  21321. _this._previousPickResult = _this._currentPickResult;
  21322. });
  21323. };
  21324. this._onKeyDown = function (evt) {
  21325. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  21326. if (_this.onPreKeyboardObservable.hasObservers()) {
  21327. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21328. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21329. if (pi.skipOnPointerObservable) {
  21330. return;
  21331. }
  21332. }
  21333. if (_this.onKeyboardObservable.hasObservers()) {
  21334. var pi = new BABYLON.KeyboardInfo(type, evt);
  21335. _this.onKeyboardObservable.notifyObservers(pi, type);
  21336. }
  21337. if (_this.actionManager) {
  21338. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21339. }
  21340. };
  21341. this._onKeyUp = function (evt) {
  21342. var type = BABYLON.KeyboardEventTypes.KEYUP;
  21343. if (_this.onPreKeyboardObservable.hasObservers()) {
  21344. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21345. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21346. if (pi.skipOnPointerObservable) {
  21347. return;
  21348. }
  21349. }
  21350. if (_this.onKeyboardObservable.hasObservers()) {
  21351. var pi = new BABYLON.KeyboardInfo(type, evt);
  21352. _this.onKeyboardObservable.notifyObservers(pi, type);
  21353. }
  21354. if (_this.actionManager) {
  21355. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21356. }
  21357. };
  21358. var engine = this.getEngine();
  21359. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  21360. if (!canvas) {
  21361. return;
  21362. }
  21363. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21364. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21365. });
  21366. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21367. if (!canvas) {
  21368. return;
  21369. }
  21370. canvas.removeEventListener("keydown", _this._onKeyDown);
  21371. canvas.removeEventListener("keyup", _this._onKeyUp);
  21372. });
  21373. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21374. var canvas = this._engine.getRenderingCanvas();
  21375. if (!canvas) {
  21376. return;
  21377. }
  21378. if (attachMove) {
  21379. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21380. // Wheel
  21381. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21382. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21383. }
  21384. if (attachDown) {
  21385. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21386. }
  21387. if (attachUp) {
  21388. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21389. }
  21390. canvas.tabIndex = 1;
  21391. };
  21392. Scene.prototype.detachControl = function () {
  21393. var engine = this.getEngine();
  21394. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21395. var canvas = engine.getRenderingCanvas();
  21396. if (!canvas) {
  21397. return;
  21398. }
  21399. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21400. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21401. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21402. if (this._onCanvasBlurObserver) {
  21403. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21404. }
  21405. if (this._onCanvasFocusObserver) {
  21406. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21407. }
  21408. // Wheel
  21409. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21410. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21411. // Keyboard
  21412. canvas.removeEventListener("keydown", this._onKeyDown);
  21413. canvas.removeEventListener("keyup", this._onKeyUp);
  21414. // Observables
  21415. this.onKeyboardObservable.clear();
  21416. this.onPreKeyboardObservable.clear();
  21417. this.onPointerObservable.clear();
  21418. this.onPrePointerObservable.clear();
  21419. };
  21420. /**
  21421. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21422. * Delay loaded resources are not taking in account
  21423. * @return true if all required resources are ready
  21424. */
  21425. Scene.prototype.isReady = function () {
  21426. if (this._isDisposed) {
  21427. return false;
  21428. }
  21429. if (this._pendingData.length > 0) {
  21430. return false;
  21431. }
  21432. var index;
  21433. var engine = this.getEngine();
  21434. // Geometries
  21435. for (index = 0; index < this._geometries.length; index++) {
  21436. var geometry = this._geometries[index];
  21437. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21438. return false;
  21439. }
  21440. }
  21441. // Meshes
  21442. for (index = 0; index < this.meshes.length; index++) {
  21443. var mesh = this.meshes[index];
  21444. if (!mesh.isEnabled()) {
  21445. continue;
  21446. }
  21447. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21448. continue;
  21449. }
  21450. if (!mesh.isReady()) {
  21451. return false;
  21452. }
  21453. // Highlight layers
  21454. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21455. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21456. var layer = _a[_i];
  21457. if (!layer.hasMesh(mesh)) {
  21458. continue;
  21459. }
  21460. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21461. var subMesh = _c[_b];
  21462. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21463. return false;
  21464. }
  21465. }
  21466. }
  21467. }
  21468. return true;
  21469. };
  21470. Scene.prototype.resetCachedMaterial = function () {
  21471. this._cachedMaterial = null;
  21472. this._cachedEffect = null;
  21473. this._cachedVisibility = null;
  21474. };
  21475. Scene.prototype.registerBeforeRender = function (func) {
  21476. this.onBeforeRenderObservable.add(func);
  21477. };
  21478. Scene.prototype.unregisterBeforeRender = function (func) {
  21479. this.onBeforeRenderObservable.removeCallback(func);
  21480. };
  21481. Scene.prototype.registerAfterRender = function (func) {
  21482. this.onAfterRenderObservable.add(func);
  21483. };
  21484. Scene.prototype.unregisterAfterRender = function (func) {
  21485. this.onAfterRenderObservable.removeCallback(func);
  21486. };
  21487. Scene.prototype._executeOnceBeforeRender = function (func) {
  21488. var _this = this;
  21489. var execFunc = function () {
  21490. func();
  21491. setTimeout(function () {
  21492. _this.unregisterBeforeRender(execFunc);
  21493. });
  21494. };
  21495. this.registerBeforeRender(execFunc);
  21496. };
  21497. /**
  21498. * The provided function will run before render once and will be disposed afterwards.
  21499. * A timeout delay can be provided so that the function will be executed in N ms.
  21500. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21501. * @param func The function to be executed.
  21502. * @param timeout optional delay in ms
  21503. */
  21504. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21505. var _this = this;
  21506. if (timeout !== undefined) {
  21507. setTimeout(function () {
  21508. _this._executeOnceBeforeRender(func);
  21509. }, timeout);
  21510. }
  21511. else {
  21512. this._executeOnceBeforeRender(func);
  21513. }
  21514. };
  21515. Scene.prototype._addPendingData = function (data) {
  21516. this._pendingData.push(data);
  21517. };
  21518. Scene.prototype._removePendingData = function (data) {
  21519. var wasLoading = this.isLoading;
  21520. var index = this._pendingData.indexOf(data);
  21521. if (index !== -1) {
  21522. this._pendingData.splice(index, 1);
  21523. }
  21524. if (wasLoading && !this.isLoading) {
  21525. this.onDataLoadedObservable.notifyObservers(this);
  21526. }
  21527. };
  21528. Scene.prototype.getWaitingItemsCount = function () {
  21529. return this._pendingData.length;
  21530. };
  21531. Object.defineProperty(Scene.prototype, "isLoading", {
  21532. get: function () {
  21533. return this._pendingData.length > 0;
  21534. },
  21535. enumerable: true,
  21536. configurable: true
  21537. });
  21538. /**
  21539. * Registers a function to be executed when the scene is ready.
  21540. * @param {Function} func - the function to be executed.
  21541. */
  21542. Scene.prototype.executeWhenReady = function (func) {
  21543. var _this = this;
  21544. this.onReadyObservable.add(func);
  21545. if (this._executeWhenReadyTimeoutId !== -1) {
  21546. return;
  21547. }
  21548. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21549. _this._checkIsReady();
  21550. }, 150);
  21551. };
  21552. Scene.prototype._checkIsReady = function () {
  21553. var _this = this;
  21554. if (this.isReady()) {
  21555. this.onReadyObservable.notifyObservers(this);
  21556. this.onReadyObservable.clear();
  21557. this._executeWhenReadyTimeoutId = -1;
  21558. return;
  21559. }
  21560. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21561. _this._checkIsReady();
  21562. }, 150);
  21563. };
  21564. // Animations
  21565. /**
  21566. * Will start the animation sequence of a given target
  21567. * @param target - the target
  21568. * @param {number} from - from which frame should animation start
  21569. * @param {number} to - till which frame should animation run.
  21570. * @param {boolean} [loop] - should the animation loop
  21571. * @param {number} [speedRatio] - the speed in which to run the animation
  21572. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21573. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21574. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21575. * See BABYLON.Animatable
  21576. */
  21577. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21578. if (speedRatio === void 0) { speedRatio = 1.0; }
  21579. if (from > to && speedRatio > 0) {
  21580. speedRatio *= -1;
  21581. }
  21582. this.stopAnimation(target);
  21583. if (!animatable) {
  21584. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21585. }
  21586. // Local animations
  21587. if (target.animations) {
  21588. animatable.appendAnimations(target, target.animations);
  21589. }
  21590. // Children animations
  21591. if (target.getAnimatables) {
  21592. var animatables = target.getAnimatables();
  21593. for (var index = 0; index < animatables.length; index++) {
  21594. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21595. }
  21596. }
  21597. animatable.reset();
  21598. return animatable;
  21599. };
  21600. /**
  21601. * Begin a new animation on a given node
  21602. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21603. * @param {BABYLON.Animation[]} defines the list of animations to start
  21604. * @param {number} from defines the initial value
  21605. * @param {number} to defines the final value
  21606. * @param {boolean} loop defines if you want animation to loop (off by default)
  21607. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21608. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21609. * @returns the list of created animatables
  21610. */
  21611. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21612. if (speedRatio === undefined) {
  21613. speedRatio = 1.0;
  21614. }
  21615. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21616. return animatable;
  21617. };
  21618. /**
  21619. * Begin a new animation on a given node and its hierarchy
  21620. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21621. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  21622. * @param {BABYLON.Animation[]} defines the list of animations to start
  21623. * @param {number} from defines the initial value
  21624. * @param {number} to defines the final value
  21625. * @param {boolean} loop defines if you want animation to loop (off by default)
  21626. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21627. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21628. * @returns the list of animatables created for all nodes
  21629. */
  21630. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21631. var children = target.getDescendants(directDescendantsOnly);
  21632. var result = [];
  21633. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21634. var child = children_1[_i];
  21635. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21636. }
  21637. return result;
  21638. };
  21639. Scene.prototype.getAnimatableByTarget = function (target) {
  21640. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21641. if (this._activeAnimatables[index].target === target) {
  21642. return this._activeAnimatables[index];
  21643. }
  21644. }
  21645. return null;
  21646. };
  21647. Object.defineProperty(Scene.prototype, "animatables", {
  21648. get: function () {
  21649. return this._activeAnimatables;
  21650. },
  21651. enumerable: true,
  21652. configurable: true
  21653. });
  21654. /**
  21655. * Will stop the animation of the given target
  21656. * @param target - the target
  21657. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21658. * @see beginAnimation
  21659. */
  21660. Scene.prototype.stopAnimation = function (target, animationName) {
  21661. var animatable = this.getAnimatableByTarget(target);
  21662. if (animatable) {
  21663. animatable.stop(animationName);
  21664. }
  21665. };
  21666. /**
  21667. * Stops and removes all animations that have been applied to the scene
  21668. */
  21669. Scene.prototype.stopAllAnimations = function () {
  21670. if (this._activeAnimatables) {
  21671. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21672. this._activeAnimatables[i].stop();
  21673. }
  21674. this._activeAnimatables = [];
  21675. }
  21676. };
  21677. Scene.prototype._animate = function () {
  21678. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21679. return;
  21680. }
  21681. // Getting time
  21682. var now = BABYLON.Tools.Now;
  21683. if (!this._animationTimeLast) {
  21684. if (this._pendingData.length > 0) {
  21685. return;
  21686. }
  21687. this._animationTimeLast = now;
  21688. }
  21689. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21690. this._animationTime += deltaTime;
  21691. this._animationTimeLast = now;
  21692. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21693. this._activeAnimatables[index]._animate(this._animationTime);
  21694. }
  21695. };
  21696. // Matrix
  21697. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21698. this._useAlternateCameraConfiguration = active;
  21699. };
  21700. Scene.prototype.getViewMatrix = function () {
  21701. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21702. };
  21703. Scene.prototype.getProjectionMatrix = function () {
  21704. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21705. };
  21706. Scene.prototype.getTransformMatrix = function () {
  21707. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21708. };
  21709. Scene.prototype.setTransformMatrix = function (view, projection) {
  21710. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21711. return;
  21712. }
  21713. this._viewUpdateFlag = view.updateFlag;
  21714. this._projectionUpdateFlag = projection.updateFlag;
  21715. this._viewMatrix = view;
  21716. this._projectionMatrix = projection;
  21717. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21718. // Update frustum
  21719. if (!this._frustumPlanes) {
  21720. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21721. }
  21722. else {
  21723. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21724. }
  21725. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21726. var otherCamera = this.activeCamera._alternateCamera;
  21727. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21728. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21729. }
  21730. if (this._sceneUbo.useUbo) {
  21731. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21732. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21733. this._sceneUbo.update();
  21734. }
  21735. };
  21736. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21737. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21738. return;
  21739. }
  21740. this._alternateViewUpdateFlag = view.updateFlag;
  21741. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21742. this._alternateViewMatrix = view;
  21743. this._alternateProjectionMatrix = projection;
  21744. if (!this._alternateTransformMatrix) {
  21745. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21746. }
  21747. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21748. if (!this._alternateSceneUbo) {
  21749. this._createAlternateUbo();
  21750. }
  21751. if (this._alternateSceneUbo.useUbo) {
  21752. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21753. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21754. this._alternateSceneUbo.update();
  21755. }
  21756. };
  21757. Scene.prototype.getSceneUniformBuffer = function () {
  21758. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21759. };
  21760. // Methods
  21761. Scene.prototype.getUniqueId = function () {
  21762. var result = Scene._uniqueIdCounter;
  21763. Scene._uniqueIdCounter++;
  21764. return result;
  21765. };
  21766. Scene.prototype.addMesh = function (newMesh) {
  21767. this.meshes.push(newMesh);
  21768. //notify the collision coordinator
  21769. if (this.collisionCoordinator) {
  21770. this.collisionCoordinator.onMeshAdded(newMesh);
  21771. }
  21772. newMesh._resyncLightSources();
  21773. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21774. };
  21775. Scene.prototype.removeMesh = function (toRemove) {
  21776. var index = this.meshes.indexOf(toRemove);
  21777. if (index !== -1) {
  21778. // Remove from the scene if mesh found
  21779. this.meshes.splice(index, 1);
  21780. }
  21781. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21782. return index;
  21783. };
  21784. Scene.prototype.addTransformNode = function (newTransformNode) {
  21785. this.transformNodes.push(newTransformNode);
  21786. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21787. };
  21788. Scene.prototype.removeTransformNode = function (toRemove) {
  21789. var index = this.transformNodes.indexOf(toRemove);
  21790. if (index !== -1) {
  21791. // Remove from the scene if found
  21792. this.transformNodes.splice(index, 1);
  21793. }
  21794. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21795. return index;
  21796. };
  21797. Scene.prototype.removeSkeleton = function (toRemove) {
  21798. var index = this.skeletons.indexOf(toRemove);
  21799. if (index !== -1) {
  21800. // Remove from the scene if found
  21801. this.skeletons.splice(index, 1);
  21802. }
  21803. return index;
  21804. };
  21805. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21806. var index = this.morphTargetManagers.indexOf(toRemove);
  21807. if (index !== -1) {
  21808. // Remove from the scene if found
  21809. this.morphTargetManagers.splice(index, 1);
  21810. }
  21811. return index;
  21812. };
  21813. Scene.prototype.removeLight = function (toRemove) {
  21814. var index = this.lights.indexOf(toRemove);
  21815. if (index !== -1) {
  21816. // Remove from meshes
  21817. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21818. var mesh = _a[_i];
  21819. mesh._removeLightSource(toRemove);
  21820. }
  21821. // Remove from the scene if mesh found
  21822. this.lights.splice(index, 1);
  21823. this.sortLightsByPriority();
  21824. }
  21825. this.onLightRemovedObservable.notifyObservers(toRemove);
  21826. return index;
  21827. };
  21828. Scene.prototype.removeCamera = function (toRemove) {
  21829. var index = this.cameras.indexOf(toRemove);
  21830. if (index !== -1) {
  21831. // Remove from the scene if mesh found
  21832. this.cameras.splice(index, 1);
  21833. }
  21834. // Remove from activeCameras
  21835. var index2 = this.activeCameras.indexOf(toRemove);
  21836. if (index2 !== -1) {
  21837. // Remove from the scene if mesh found
  21838. this.activeCameras.splice(index2, 1);
  21839. }
  21840. // Reset the activeCamera
  21841. if (this.activeCamera === toRemove) {
  21842. if (this.cameras.length > 0) {
  21843. this.activeCamera = this.cameras[0];
  21844. }
  21845. else {
  21846. this.activeCamera = null;
  21847. }
  21848. }
  21849. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21850. return index;
  21851. };
  21852. Scene.prototype.removeParticleSystem = function (toRemove) {
  21853. var index = this.particleSystems.indexOf(toRemove);
  21854. if (index !== -1) {
  21855. this.particleSystems.splice(index, 1);
  21856. }
  21857. return index;
  21858. };
  21859. ;
  21860. Scene.prototype.removeAnimation = function (toRemove) {
  21861. var index = this.animations.indexOf(toRemove);
  21862. if (index !== -1) {
  21863. this.animations.splice(index, 1);
  21864. }
  21865. return index;
  21866. };
  21867. ;
  21868. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21869. var index = this.multiMaterials.indexOf(toRemove);
  21870. if (index !== -1) {
  21871. this.multiMaterials.splice(index, 1);
  21872. }
  21873. return index;
  21874. };
  21875. ;
  21876. Scene.prototype.removeMaterial = function (toRemove) {
  21877. var index = this.materials.indexOf(toRemove);
  21878. if (index !== -1) {
  21879. this.materials.splice(index, 1);
  21880. }
  21881. return index;
  21882. };
  21883. ;
  21884. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21885. var index = this.lensFlareSystems.indexOf(toRemove);
  21886. if (index !== -1) {
  21887. this.lensFlareSystems.splice(index, 1);
  21888. }
  21889. return index;
  21890. };
  21891. ;
  21892. Scene.prototype.removeActionManager = function (toRemove) {
  21893. var index = this._actionManagers.indexOf(toRemove);
  21894. if (index !== -1) {
  21895. this._actionManagers.splice(index, 1);
  21896. }
  21897. return index;
  21898. };
  21899. ;
  21900. Scene.prototype.addLight = function (newLight) {
  21901. this.lights.push(newLight);
  21902. this.sortLightsByPriority();
  21903. // Add light to all meshes (To support if the light is removed and then readded)
  21904. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21905. var mesh = _a[_i];
  21906. if (mesh._lightSources.indexOf(newLight) === -1) {
  21907. mesh._lightSources.push(newLight);
  21908. mesh._resyncLightSources();
  21909. }
  21910. }
  21911. this.onNewLightAddedObservable.notifyObservers(newLight);
  21912. };
  21913. Scene.prototype.sortLightsByPriority = function () {
  21914. if (this.requireLightSorting) {
  21915. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  21916. }
  21917. };
  21918. Scene.prototype.addCamera = function (newCamera) {
  21919. this.cameras.push(newCamera);
  21920. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21921. };
  21922. Scene.prototype.addSkeleton = function (newSkeleton) {
  21923. this.skeletons.push(newSkeleton);
  21924. };
  21925. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21926. this.particleSystems.push(newParticleSystem);
  21927. };
  21928. Scene.prototype.addAnimation = function (newAnimation) {
  21929. this.animations.push(newAnimation);
  21930. };
  21931. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21932. this.multiMaterials.push(newMultiMaterial);
  21933. };
  21934. Scene.prototype.addMaterial = function (newMaterial) {
  21935. this.materials.push(newMaterial);
  21936. };
  21937. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21938. this.morphTargetManagers.push(newMorphTargetManager);
  21939. };
  21940. Scene.prototype.addGeometry = function (newGeometrie) {
  21941. this._geometries.push(newGeometrie);
  21942. };
  21943. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21944. this.lensFlareSystems.push(newLensFlareSystem);
  21945. };
  21946. Scene.prototype.addActionManager = function (newActionManager) {
  21947. this._actionManagers.push(newActionManager);
  21948. };
  21949. /**
  21950. * Switch active camera
  21951. * @param {Camera} newCamera - new active camera
  21952. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21953. */
  21954. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21955. if (attachControl === void 0) { attachControl = true; }
  21956. var canvas = this._engine.getRenderingCanvas();
  21957. if (!canvas) {
  21958. return;
  21959. }
  21960. if (this.activeCamera) {
  21961. this.activeCamera.detachControl(canvas);
  21962. }
  21963. this.activeCamera = newCamera;
  21964. if (attachControl) {
  21965. newCamera.attachControl(canvas);
  21966. }
  21967. };
  21968. /**
  21969. * sets the active camera of the scene using its ID
  21970. * @param {string} id - the camera's ID
  21971. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21972. * @see activeCamera
  21973. */
  21974. Scene.prototype.setActiveCameraByID = function (id) {
  21975. var camera = this.getCameraByID(id);
  21976. if (camera) {
  21977. this.activeCamera = camera;
  21978. return camera;
  21979. }
  21980. return null;
  21981. };
  21982. /**
  21983. * sets the active camera of the scene using its name
  21984. * @param {string} name - the camera's name
  21985. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21986. * @see activeCamera
  21987. */
  21988. Scene.prototype.setActiveCameraByName = function (name) {
  21989. var camera = this.getCameraByName(name);
  21990. if (camera) {
  21991. this.activeCamera = camera;
  21992. return camera;
  21993. }
  21994. return null;
  21995. };
  21996. /**
  21997. * get an animation group using its name
  21998. * @param {string} the material's name
  21999. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22000. */
  22001. Scene.prototype.getAnimationGroupByName = function (name) {
  22002. for (var index = 0; index < this.animationGroups.length; index++) {
  22003. if (this.animationGroups[index].name === name) {
  22004. return this.animationGroups[index];
  22005. }
  22006. }
  22007. return null;
  22008. };
  22009. /**
  22010. * get a material using its id
  22011. * @param {string} the material's ID
  22012. * @return {BABYLON.Material|null} the material or null if none found.
  22013. */
  22014. Scene.prototype.getMaterialByID = function (id) {
  22015. for (var index = 0; index < this.materials.length; index++) {
  22016. if (this.materials[index].id === id) {
  22017. return this.materials[index];
  22018. }
  22019. }
  22020. return null;
  22021. };
  22022. /**
  22023. * get a material using its name
  22024. * @param {string} the material's name
  22025. * @return {BABYLON.Material|null} the material or null if none found.
  22026. */
  22027. Scene.prototype.getMaterialByName = function (name) {
  22028. for (var index = 0; index < this.materials.length; index++) {
  22029. if (this.materials[index].name === name) {
  22030. return this.materials[index];
  22031. }
  22032. }
  22033. return null;
  22034. };
  22035. Scene.prototype.getLensFlareSystemByName = function (name) {
  22036. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22037. if (this.lensFlareSystems[index].name === name) {
  22038. return this.lensFlareSystems[index];
  22039. }
  22040. }
  22041. return null;
  22042. };
  22043. Scene.prototype.getLensFlareSystemByID = function (id) {
  22044. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22045. if (this.lensFlareSystems[index].id === id) {
  22046. return this.lensFlareSystems[index];
  22047. }
  22048. }
  22049. return null;
  22050. };
  22051. Scene.prototype.getCameraByID = function (id) {
  22052. for (var index = 0; index < this.cameras.length; index++) {
  22053. if (this.cameras[index].id === id) {
  22054. return this.cameras[index];
  22055. }
  22056. }
  22057. return null;
  22058. };
  22059. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22060. for (var index = 0; index < this.cameras.length; index++) {
  22061. if (this.cameras[index].uniqueId === uniqueId) {
  22062. return this.cameras[index];
  22063. }
  22064. }
  22065. return null;
  22066. };
  22067. /**
  22068. * get a camera using its name
  22069. * @param {string} the camera's name
  22070. * @return {BABYLON.Camera|null} the camera or null if none found.
  22071. */
  22072. Scene.prototype.getCameraByName = function (name) {
  22073. for (var index = 0; index < this.cameras.length; index++) {
  22074. if (this.cameras[index].name === name) {
  22075. return this.cameras[index];
  22076. }
  22077. }
  22078. return null;
  22079. };
  22080. /**
  22081. * get a bone using its id
  22082. * @param {string} the bone's id
  22083. * @return {BABYLON.Bone|null} the bone or null if not found
  22084. */
  22085. Scene.prototype.getBoneByID = function (id) {
  22086. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22087. var skeleton = this.skeletons[skeletonIndex];
  22088. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22089. if (skeleton.bones[boneIndex].id === id) {
  22090. return skeleton.bones[boneIndex];
  22091. }
  22092. }
  22093. }
  22094. return null;
  22095. };
  22096. /**
  22097. * get a bone using its id
  22098. * @param {string} the bone's name
  22099. * @return {BABYLON.Bone|null} the bone or null if not found
  22100. */
  22101. Scene.prototype.getBoneByName = function (name) {
  22102. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22103. var skeleton = this.skeletons[skeletonIndex];
  22104. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22105. if (skeleton.bones[boneIndex].name === name) {
  22106. return skeleton.bones[boneIndex];
  22107. }
  22108. }
  22109. }
  22110. return null;
  22111. };
  22112. /**
  22113. * get a light node using its name
  22114. * @param {string} the light's name
  22115. * @return {BABYLON.Light|null} the light or null if none found.
  22116. */
  22117. Scene.prototype.getLightByName = function (name) {
  22118. for (var index = 0; index < this.lights.length; index++) {
  22119. if (this.lights[index].name === name) {
  22120. return this.lights[index];
  22121. }
  22122. }
  22123. return null;
  22124. };
  22125. /**
  22126. * get a light node using its ID
  22127. * @param {string} the light's id
  22128. * @return {BABYLON.Light|null} the light or null if none found.
  22129. */
  22130. Scene.prototype.getLightByID = function (id) {
  22131. for (var index = 0; index < this.lights.length; index++) {
  22132. if (this.lights[index].id === id) {
  22133. return this.lights[index];
  22134. }
  22135. }
  22136. return null;
  22137. };
  22138. /**
  22139. * get a light node using its scene-generated unique ID
  22140. * @param {number} the light's unique id
  22141. * @return {BABYLON.Light|null} the light or null if none found.
  22142. */
  22143. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22144. for (var index = 0; index < this.lights.length; index++) {
  22145. if (this.lights[index].uniqueId === uniqueId) {
  22146. return this.lights[index];
  22147. }
  22148. }
  22149. return null;
  22150. };
  22151. /**
  22152. * get a particle system by id
  22153. * @param id {number} the particle system id
  22154. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22155. */
  22156. Scene.prototype.getParticleSystemByID = function (id) {
  22157. for (var index = 0; index < this.particleSystems.length; index++) {
  22158. if (this.particleSystems[index].id === id) {
  22159. return this.particleSystems[index];
  22160. }
  22161. }
  22162. return null;
  22163. };
  22164. /**
  22165. * get a geometry using its ID
  22166. * @param {string} the geometry's id
  22167. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22168. */
  22169. Scene.prototype.getGeometryByID = function (id) {
  22170. for (var index = 0; index < this._geometries.length; index++) {
  22171. if (this._geometries[index].id === id) {
  22172. return this._geometries[index];
  22173. }
  22174. }
  22175. return null;
  22176. };
  22177. /**
  22178. * add a new geometry to this scene.
  22179. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22180. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22181. * @return {boolean} was the geometry added or not
  22182. */
  22183. Scene.prototype.pushGeometry = function (geometry, force) {
  22184. if (!force && this.getGeometryByID(geometry.id)) {
  22185. return false;
  22186. }
  22187. this._geometries.push(geometry);
  22188. //notify the collision coordinator
  22189. if (this.collisionCoordinator) {
  22190. this.collisionCoordinator.onGeometryAdded(geometry);
  22191. }
  22192. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22193. return true;
  22194. };
  22195. /**
  22196. * Removes an existing geometry
  22197. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22198. * @return {boolean} was the geometry removed or not
  22199. */
  22200. Scene.prototype.removeGeometry = function (geometry) {
  22201. var index = this._geometries.indexOf(geometry);
  22202. if (index > -1) {
  22203. this._geometries.splice(index, 1);
  22204. //notify the collision coordinator
  22205. if (this.collisionCoordinator) {
  22206. this.collisionCoordinator.onGeometryDeleted(geometry);
  22207. }
  22208. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22209. return true;
  22210. }
  22211. return false;
  22212. };
  22213. Scene.prototype.getGeometries = function () {
  22214. return this._geometries;
  22215. };
  22216. /**
  22217. * Get the first added mesh found of a given ID
  22218. * @param {string} id - the id to search for
  22219. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22220. */
  22221. Scene.prototype.getMeshByID = function (id) {
  22222. for (var index = 0; index < this.meshes.length; index++) {
  22223. if (this.meshes[index].id === id) {
  22224. return this.meshes[index];
  22225. }
  22226. }
  22227. return null;
  22228. };
  22229. Scene.prototype.getMeshesByID = function (id) {
  22230. return this.meshes.filter(function (m) {
  22231. return m.id === id;
  22232. });
  22233. };
  22234. /**
  22235. * Get the first added transform node found of a given ID
  22236. * @param {string} id - the id to search for
  22237. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22238. */
  22239. Scene.prototype.getTransformNodeByID = function (id) {
  22240. for (var index = 0; index < this.transformNodes.length; index++) {
  22241. if (this.transformNodes[index].id === id) {
  22242. return this.transformNodes[index];
  22243. }
  22244. }
  22245. return null;
  22246. };
  22247. Scene.prototype.getTransformNodesByID = function (id) {
  22248. return this.transformNodes.filter(function (m) {
  22249. return m.id === id;
  22250. });
  22251. };
  22252. /**
  22253. * Get a mesh with its auto-generated unique id
  22254. * @param {number} uniqueId - the unique id to search for
  22255. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22256. */
  22257. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22258. for (var index = 0; index < this.meshes.length; index++) {
  22259. if (this.meshes[index].uniqueId === uniqueId) {
  22260. return this.meshes[index];
  22261. }
  22262. }
  22263. return null;
  22264. };
  22265. /**
  22266. * Get a the last added mesh found of a given ID
  22267. * @param {string} id - the id to search for
  22268. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22269. */
  22270. Scene.prototype.getLastMeshByID = function (id) {
  22271. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22272. if (this.meshes[index].id === id) {
  22273. return this.meshes[index];
  22274. }
  22275. }
  22276. return null;
  22277. };
  22278. /**
  22279. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22280. * @param {string} id - the id to search for
  22281. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22282. */
  22283. Scene.prototype.getLastEntryByID = function (id) {
  22284. var index;
  22285. for (index = this.meshes.length - 1; index >= 0; index--) {
  22286. if (this.meshes[index].id === id) {
  22287. return this.meshes[index];
  22288. }
  22289. }
  22290. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22291. if (this.transformNodes[index].id === id) {
  22292. return this.transformNodes[index];
  22293. }
  22294. }
  22295. for (index = this.cameras.length - 1; index >= 0; index--) {
  22296. if (this.cameras[index].id === id) {
  22297. return this.cameras[index];
  22298. }
  22299. }
  22300. for (index = this.lights.length - 1; index >= 0; index--) {
  22301. if (this.lights[index].id === id) {
  22302. return this.lights[index];
  22303. }
  22304. }
  22305. return null;
  22306. };
  22307. Scene.prototype.getNodeByID = function (id) {
  22308. var mesh = this.getMeshByID(id);
  22309. if (mesh) {
  22310. return mesh;
  22311. }
  22312. var light = this.getLightByID(id);
  22313. if (light) {
  22314. return light;
  22315. }
  22316. var camera = this.getCameraByID(id);
  22317. if (camera) {
  22318. return camera;
  22319. }
  22320. var bone = this.getBoneByID(id);
  22321. return bone;
  22322. };
  22323. Scene.prototype.getNodeByName = function (name) {
  22324. var mesh = this.getMeshByName(name);
  22325. if (mesh) {
  22326. return mesh;
  22327. }
  22328. var light = this.getLightByName(name);
  22329. if (light) {
  22330. return light;
  22331. }
  22332. var camera = this.getCameraByName(name);
  22333. if (camera) {
  22334. return camera;
  22335. }
  22336. var bone = this.getBoneByName(name);
  22337. return bone;
  22338. };
  22339. Scene.prototype.getMeshByName = function (name) {
  22340. for (var index = 0; index < this.meshes.length; index++) {
  22341. if (this.meshes[index].name === name) {
  22342. return this.meshes[index];
  22343. }
  22344. }
  22345. return null;
  22346. };
  22347. Scene.prototype.getTransformNodeByName = function (name) {
  22348. for (var index = 0; index < this.transformNodes.length; index++) {
  22349. if (this.transformNodes[index].name === name) {
  22350. return this.transformNodes[index];
  22351. }
  22352. }
  22353. return null;
  22354. };
  22355. Scene.prototype.getSoundByName = function (name) {
  22356. var index;
  22357. if (BABYLON.AudioEngine) {
  22358. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22359. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22360. return this.mainSoundTrack.soundCollection[index];
  22361. }
  22362. }
  22363. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22364. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22365. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22366. return this.soundTracks[sdIndex].soundCollection[index];
  22367. }
  22368. }
  22369. }
  22370. }
  22371. return null;
  22372. };
  22373. Scene.prototype.getLastSkeletonByID = function (id) {
  22374. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22375. if (this.skeletons[index].id === id) {
  22376. return this.skeletons[index];
  22377. }
  22378. }
  22379. return null;
  22380. };
  22381. Scene.prototype.getSkeletonById = function (id) {
  22382. for (var index = 0; index < this.skeletons.length; index++) {
  22383. if (this.skeletons[index].id === id) {
  22384. return this.skeletons[index];
  22385. }
  22386. }
  22387. return null;
  22388. };
  22389. Scene.prototype.getSkeletonByName = function (name) {
  22390. for (var index = 0; index < this.skeletons.length; index++) {
  22391. if (this.skeletons[index].name === name) {
  22392. return this.skeletons[index];
  22393. }
  22394. }
  22395. return null;
  22396. };
  22397. Scene.prototype.getMorphTargetManagerById = function (id) {
  22398. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22399. if (this.morphTargetManagers[index].uniqueId === id) {
  22400. return this.morphTargetManagers[index];
  22401. }
  22402. }
  22403. return null;
  22404. };
  22405. Scene.prototype.isActiveMesh = function (mesh) {
  22406. return (this._activeMeshes.indexOf(mesh) !== -1);
  22407. };
  22408. /**
  22409. * Return a the first highlight layer of the scene with a given name.
  22410. * @param name The name of the highlight layer to look for.
  22411. * @return The highlight layer if found otherwise null.
  22412. */
  22413. Scene.prototype.getHighlightLayerByName = function (name) {
  22414. for (var index = 0; index < this.highlightLayers.length; index++) {
  22415. if (this.highlightLayers[index].name === name) {
  22416. return this.highlightLayers[index];
  22417. }
  22418. }
  22419. return null;
  22420. };
  22421. Object.defineProperty(Scene.prototype, "uid", {
  22422. /**
  22423. * Return a unique id as a string which can serve as an identifier for the scene
  22424. */
  22425. get: function () {
  22426. if (!this._uid) {
  22427. this._uid = BABYLON.Tools.RandomId();
  22428. }
  22429. return this._uid;
  22430. },
  22431. enumerable: true,
  22432. configurable: true
  22433. });
  22434. /**
  22435. * Add an externaly attached data from its key.
  22436. * This method call will fail and return false, if such key already exists.
  22437. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22438. * @param key the unique key that identifies the data
  22439. * @param data the data object to associate to the key for this Engine instance
  22440. * @return true if no such key were already present and the data was added successfully, false otherwise
  22441. */
  22442. Scene.prototype.addExternalData = function (key, data) {
  22443. if (!this._externalData) {
  22444. this._externalData = new BABYLON.StringDictionary();
  22445. }
  22446. return this._externalData.add(key, data);
  22447. };
  22448. /**
  22449. * Get an externaly attached data from its key
  22450. * @param key the unique key that identifies the data
  22451. * @return the associated data, if present (can be null), or undefined if not present
  22452. */
  22453. Scene.prototype.getExternalData = function (key) {
  22454. if (!this._externalData) {
  22455. return null;
  22456. }
  22457. return this._externalData.get(key);
  22458. };
  22459. /**
  22460. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22461. * @param key the unique key that identifies the data
  22462. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22463. * @return the associated data, can be null if the factory returned null.
  22464. */
  22465. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22466. if (!this._externalData) {
  22467. this._externalData = new BABYLON.StringDictionary();
  22468. }
  22469. return this._externalData.getOrAddWithFactory(key, factory);
  22470. };
  22471. /**
  22472. * Remove an externaly attached data from the Engine instance
  22473. * @param key the unique key that identifies the data
  22474. * @return true if the data was successfully removed, false if it doesn't exist
  22475. */
  22476. Scene.prototype.removeExternalData = function (key) {
  22477. return this._externalData.remove(key);
  22478. };
  22479. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22480. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22481. if (mesh.showSubMeshesBoundingBox) {
  22482. var boundingInfo = subMesh.getBoundingInfo();
  22483. if (boundingInfo !== null && boundingInfo !== undefined) {
  22484. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22485. }
  22486. }
  22487. var material = subMesh.getMaterial();
  22488. if (material !== null && material !== undefined) {
  22489. // Render targets
  22490. if (material.getRenderTargetTextures !== undefined) {
  22491. if (this._processedMaterials.indexOf(material) === -1) {
  22492. this._processedMaterials.push(material);
  22493. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22494. }
  22495. }
  22496. // Dispatch
  22497. this._activeIndices.addCount(subMesh.indexCount, false);
  22498. this._renderingManager.dispatch(subMesh, mesh, material);
  22499. }
  22500. }
  22501. };
  22502. Scene.prototype._isInIntermediateRendering = function () {
  22503. return this._intermediateRendering;
  22504. };
  22505. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22506. this._activeMeshCandidateProvider = provider;
  22507. };
  22508. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22509. return this._activeMeshCandidateProvider;
  22510. };
  22511. /**
  22512. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22513. */
  22514. Scene.prototype.freezeActiveMeshes = function () {
  22515. this._evaluateActiveMeshes();
  22516. this._activeMeshesFrozen = true;
  22517. return this;
  22518. };
  22519. /**
  22520. * Use this function to restart evaluating active meshes on every frame
  22521. */
  22522. Scene.prototype.unfreezeActiveMeshes = function () {
  22523. this._activeMeshesFrozen = false;
  22524. return this;
  22525. };
  22526. Scene.prototype._evaluateActiveMeshes = function () {
  22527. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22528. return;
  22529. }
  22530. if (!this.activeCamera) {
  22531. return;
  22532. }
  22533. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22534. this.activeCamera._activeMeshes.reset();
  22535. this._activeMeshes.reset();
  22536. this._renderingManager.reset();
  22537. this._processedMaterials.reset();
  22538. this._activeParticleSystems.reset();
  22539. this._activeSkeletons.reset();
  22540. this._softwareSkinnedMeshes.reset();
  22541. if (this._boundingBoxRenderer) {
  22542. this._boundingBoxRenderer.reset();
  22543. }
  22544. // Meshes
  22545. var meshes;
  22546. var len;
  22547. var checkIsEnabled = true;
  22548. // Determine mesh candidates
  22549. if (this._activeMeshCandidateProvider !== undefined) {
  22550. // Use _activeMeshCandidateProvider
  22551. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22552. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22553. if (meshes !== undefined) {
  22554. len = meshes.length;
  22555. }
  22556. else {
  22557. len = 0;
  22558. }
  22559. }
  22560. else if (this._selectionOctree !== undefined) {
  22561. // Octree
  22562. var selection = this._selectionOctree.select(this._frustumPlanes);
  22563. meshes = selection.data;
  22564. len = selection.length;
  22565. }
  22566. else {
  22567. // Full scene traversal
  22568. len = this.meshes.length;
  22569. meshes = this.meshes;
  22570. }
  22571. // Check each mesh
  22572. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22573. mesh = meshes[meshIndex];
  22574. if (mesh.isBlocked) {
  22575. continue;
  22576. }
  22577. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22578. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22579. continue;
  22580. }
  22581. mesh.computeWorldMatrix();
  22582. // Intersections
  22583. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22584. this._meshesForIntersections.pushNoDuplicate(mesh);
  22585. }
  22586. // Switch to current LOD
  22587. meshLOD = mesh.getLOD(this.activeCamera);
  22588. if (meshLOD === undefined || meshLOD === null) {
  22589. continue;
  22590. }
  22591. mesh._preActivate();
  22592. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22593. this._activeMeshes.push(mesh);
  22594. this.activeCamera._activeMeshes.push(mesh);
  22595. mesh._activate(this._renderId);
  22596. if (meshLOD !== mesh) {
  22597. meshLOD._activate(this._renderId);
  22598. }
  22599. this._activeMesh(mesh, meshLOD);
  22600. }
  22601. }
  22602. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22603. // Particle systems
  22604. if (this.particlesEnabled) {
  22605. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22606. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22607. var particleSystem = this.particleSystems[particleIndex];
  22608. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22609. continue;
  22610. }
  22611. var emitter = particleSystem.emitter;
  22612. if (!emitter.position || emitter.isEnabled()) {
  22613. this._activeParticleSystems.push(particleSystem);
  22614. particleSystem.animate();
  22615. this._renderingManager.dispatchParticles(particleSystem);
  22616. }
  22617. }
  22618. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22619. }
  22620. };
  22621. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22622. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22623. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22624. mesh.skeleton.prepare();
  22625. }
  22626. if (!mesh.computeBonesUsingShaders) {
  22627. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22628. }
  22629. }
  22630. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22631. var boundingInfo = sourceMesh.getBoundingInfo();
  22632. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22633. }
  22634. if (mesh !== undefined && mesh !== null
  22635. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22636. // Submeshes Octrees
  22637. var len;
  22638. var subMeshes;
  22639. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22640. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22641. len = intersections.length;
  22642. subMeshes = intersections.data;
  22643. }
  22644. else {
  22645. subMeshes = mesh.subMeshes;
  22646. len = subMeshes.length;
  22647. }
  22648. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22649. subMesh = subMeshes[subIndex];
  22650. this._evaluateSubMesh(subMesh, mesh);
  22651. }
  22652. }
  22653. };
  22654. Scene.prototype.updateTransformMatrix = function (force) {
  22655. if (!this.activeCamera) {
  22656. return;
  22657. }
  22658. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22659. };
  22660. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22661. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22662. };
  22663. Scene.prototype._renderForCamera = function (camera) {
  22664. if (camera && camera._skipRendering) {
  22665. return;
  22666. }
  22667. var engine = this._engine;
  22668. this.activeCamera = camera;
  22669. if (!this.activeCamera)
  22670. throw new Error("Active camera not set");
  22671. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22672. // Viewport
  22673. engine.setViewport(this.activeCamera.viewport);
  22674. // Camera
  22675. this.resetCachedMaterial();
  22676. this._renderId++;
  22677. this.activeCamera.update();
  22678. this.updateTransformMatrix();
  22679. if (camera._alternateCamera) {
  22680. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22681. this._alternateRendering = true;
  22682. }
  22683. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22684. // Meshes
  22685. this._evaluateActiveMeshes();
  22686. // Software skinning
  22687. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22688. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22689. mesh.applySkeleton(mesh.skeleton);
  22690. }
  22691. // Render targets
  22692. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22693. var needsRestoreFrameBuffer = false;
  22694. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22695. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22696. }
  22697. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22698. this._intermediateRendering = true;
  22699. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22700. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22701. var renderTarget = this._renderTargets.data[renderIndex];
  22702. if (renderTarget._shouldRender()) {
  22703. this._renderId++;
  22704. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22705. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22706. }
  22707. }
  22708. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22709. this._intermediateRendering = false;
  22710. this._renderId++;
  22711. needsRestoreFrameBuffer = true; // Restore back buffer
  22712. }
  22713. // Render HighlightLayer Texture
  22714. var stencilState = this._engine.getStencilBuffer();
  22715. var renderhighlights = false;
  22716. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22717. this._intermediateRendering = true;
  22718. for (var i = 0; i < this.highlightLayers.length; i++) {
  22719. var highlightLayer = this.highlightLayers[i];
  22720. if (highlightLayer.shouldRender() &&
  22721. (!highlightLayer.camera ||
  22722. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22723. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22724. renderhighlights = true;
  22725. var renderTarget = highlightLayer._mainTexture;
  22726. if (renderTarget._shouldRender()) {
  22727. this._renderId++;
  22728. renderTarget.render(false, false);
  22729. needsRestoreFrameBuffer = true;
  22730. }
  22731. }
  22732. }
  22733. this._intermediateRendering = false;
  22734. this._renderId++;
  22735. }
  22736. if (needsRestoreFrameBuffer) {
  22737. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22738. }
  22739. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22740. // Prepare Frame
  22741. this.postProcessManager._prepareFrame();
  22742. // Backgrounds
  22743. var layerIndex;
  22744. var layer;
  22745. if (this.layers.length) {
  22746. engine.setDepthBuffer(false);
  22747. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22748. layer = this.layers[layerIndex];
  22749. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22750. layer.render();
  22751. }
  22752. }
  22753. engine.setDepthBuffer(true);
  22754. }
  22755. // Activate HighlightLayer stencil
  22756. if (renderhighlights) {
  22757. this._engine.setStencilBuffer(true);
  22758. }
  22759. // Render
  22760. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22761. this._renderingManager.render(null, null, true, true);
  22762. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22763. // Restore HighlightLayer stencil
  22764. if (renderhighlights) {
  22765. this._engine.setStencilBuffer(stencilState);
  22766. }
  22767. // Bounding boxes
  22768. if (this._boundingBoxRenderer) {
  22769. this._boundingBoxRenderer.render();
  22770. }
  22771. // Lens flares
  22772. if (this.lensFlaresEnabled) {
  22773. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22774. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22775. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22776. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22777. lensFlareSystem.render();
  22778. }
  22779. }
  22780. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22781. }
  22782. // Foregrounds
  22783. if (this.layers.length) {
  22784. engine.setDepthBuffer(false);
  22785. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22786. layer = this.layers[layerIndex];
  22787. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22788. layer.render();
  22789. }
  22790. }
  22791. engine.setDepthBuffer(true);
  22792. }
  22793. // Highlight Layer
  22794. if (renderhighlights) {
  22795. engine.setDepthBuffer(false);
  22796. for (var i = 0; i < this.highlightLayers.length; i++) {
  22797. if (this.highlightLayers[i].shouldRender()) {
  22798. this.highlightLayers[i].render();
  22799. }
  22800. }
  22801. engine.setDepthBuffer(true);
  22802. }
  22803. // Finalize frame
  22804. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22805. // Reset some special arrays
  22806. this._renderTargets.reset();
  22807. this._alternateRendering = false;
  22808. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22809. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22810. };
  22811. Scene.prototype._processSubCameras = function (camera) {
  22812. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22813. this._renderForCamera(camera);
  22814. return;
  22815. }
  22816. // Update camera
  22817. if (this.activeCamera) {
  22818. this.activeCamera.update();
  22819. }
  22820. // rig cameras
  22821. for (var index = 0; index < camera._rigCameras.length; index++) {
  22822. this._renderForCamera(camera._rigCameras[index]);
  22823. }
  22824. this.activeCamera = camera;
  22825. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22826. };
  22827. Scene.prototype._checkIntersections = function () {
  22828. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22829. var sourceMesh = this._meshesForIntersections.data[index];
  22830. if (!sourceMesh.actionManager) {
  22831. continue;
  22832. }
  22833. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22834. var action = sourceMesh.actionManager.actions[actionIndex];
  22835. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22836. var parameters = action.getTriggerParameter();
  22837. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22838. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22839. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22840. if (areIntersecting && currentIntersectionInProgress === -1) {
  22841. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22842. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22843. sourceMesh._intersectionsInProgress.push(otherMesh);
  22844. }
  22845. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22846. sourceMesh._intersectionsInProgress.push(otherMesh);
  22847. }
  22848. }
  22849. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22850. //They intersected, and now they don't.
  22851. //is this trigger an exit trigger? execute an event.
  22852. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22853. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22854. }
  22855. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22856. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22857. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22858. }
  22859. }
  22860. }
  22861. }
  22862. }
  22863. };
  22864. Scene.prototype.render = function () {
  22865. if (this.isDisposed) {
  22866. return;
  22867. }
  22868. this._activeParticles.fetchNewFrame();
  22869. this._totalVertices.fetchNewFrame();
  22870. this._activeIndices.fetchNewFrame();
  22871. this._activeBones.fetchNewFrame();
  22872. this._meshesForIntersections.reset();
  22873. this.resetCachedMaterial();
  22874. this.onBeforeAnimationsObservable.notifyObservers(this);
  22875. // Actions
  22876. if (this.actionManager) {
  22877. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22878. }
  22879. //Simplification Queue
  22880. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22881. this.simplificationQueue.executeNext();
  22882. }
  22883. if (this._engine.isDeterministicLockStep()) {
  22884. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22885. var defaultFPS = (60.0 / 1000.0);
  22886. var defaultFrameTime = 1000 / 60; // frame time in MS
  22887. if (this._physicsEngine) {
  22888. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22889. }
  22890. var stepsTaken = 0;
  22891. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22892. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22893. internalSteps = Math.min(internalSteps, maxSubSteps);
  22894. do {
  22895. this.onBeforeStepObservable.notifyObservers(this);
  22896. // Animations
  22897. this._animationRatio = defaultFrameTime * defaultFPS;
  22898. this._animate();
  22899. this.onAfterAnimationsObservable.notifyObservers(this);
  22900. // Physics
  22901. if (this._physicsEngine) {
  22902. this.onBeforePhysicsObservable.notifyObservers(this);
  22903. this._physicsEngine._step(defaultFrameTime / 1000);
  22904. this.onAfterPhysicsObservable.notifyObservers(this);
  22905. }
  22906. this.onAfterStepObservable.notifyObservers(this);
  22907. this._currentStepId++;
  22908. stepsTaken++;
  22909. deltaTime -= defaultFrameTime;
  22910. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22911. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22912. }
  22913. else {
  22914. // Animations
  22915. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22916. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22917. this._animate();
  22918. this.onAfterAnimationsObservable.notifyObservers(this);
  22919. // Physics
  22920. if (this._physicsEngine) {
  22921. this.onBeforePhysicsObservable.notifyObservers(this);
  22922. this._physicsEngine._step(deltaTime / 1000.0);
  22923. this.onAfterPhysicsObservable.notifyObservers(this);
  22924. }
  22925. }
  22926. // update gamepad manager
  22927. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22928. this._gamepadManager._checkGamepadsStatus();
  22929. }
  22930. // Before render
  22931. this.onBeforeRenderObservable.notifyObservers(this);
  22932. // Customs render targets
  22933. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22934. var engine = this.getEngine();
  22935. var currentActiveCamera = this.activeCamera;
  22936. if (this.renderTargetsEnabled) {
  22937. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22938. this._intermediateRendering = true;
  22939. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22940. var renderTarget = this.customRenderTargets[customIndex];
  22941. if (renderTarget._shouldRender()) {
  22942. this._renderId++;
  22943. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22944. if (!this.activeCamera)
  22945. throw new Error("Active camera not set");
  22946. // Viewport
  22947. engine.setViewport(this.activeCamera.viewport);
  22948. // Camera
  22949. this.updateTransformMatrix();
  22950. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22951. }
  22952. }
  22953. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22954. this._intermediateRendering = false;
  22955. this._renderId++;
  22956. }
  22957. // Restore back buffer
  22958. if (this.customRenderTargets.length > 0) {
  22959. engine.restoreDefaultFramebuffer();
  22960. }
  22961. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22962. this.activeCamera = currentActiveCamera;
  22963. // Procedural textures
  22964. if (this.proceduralTexturesEnabled) {
  22965. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22966. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22967. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22968. if (proceduralTexture._shouldRender()) {
  22969. proceduralTexture.render();
  22970. }
  22971. }
  22972. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22973. }
  22974. // Clear
  22975. if (this.autoClearDepthAndStencil || this.autoClear) {
  22976. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22977. }
  22978. // Shadows
  22979. if (this.shadowsEnabled) {
  22980. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22981. var light = this.lights[lightIndex];
  22982. var shadowGenerator = light.getShadowGenerator();
  22983. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22984. var shadowMap = (shadowGenerator.getShadowMap());
  22985. if (this.textures.indexOf(shadowMap) !== -1) {
  22986. this._renderTargets.push(shadowMap);
  22987. }
  22988. }
  22989. }
  22990. }
  22991. // Depth renderer
  22992. if (this._depthRenderer) {
  22993. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22994. }
  22995. // Geometry renderer
  22996. if (this._geometryBufferRenderer) {
  22997. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22998. }
  22999. // RenderPipeline
  23000. if (this._postProcessRenderPipelineManager) {
  23001. this._postProcessRenderPipelineManager.update();
  23002. }
  23003. // Multi-cameras?
  23004. if (this.activeCameras.length > 0) {
  23005. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23006. if (cameraIndex > 0) {
  23007. this._engine.clear(null, false, true, true);
  23008. }
  23009. this._processSubCameras(this.activeCameras[cameraIndex]);
  23010. }
  23011. }
  23012. else {
  23013. if (!this.activeCamera) {
  23014. throw new Error("No camera defined");
  23015. }
  23016. this._processSubCameras(this.activeCamera);
  23017. }
  23018. // Intersection checks
  23019. this._checkIntersections();
  23020. // Update the audio listener attached to the camera
  23021. if (BABYLON.AudioEngine) {
  23022. this._updateAudioParameters();
  23023. }
  23024. // After render
  23025. if (this.afterRender) {
  23026. this.afterRender();
  23027. }
  23028. this.onAfterRenderObservable.notifyObservers(this);
  23029. // Cleaning
  23030. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23031. var data = this._toBeDisposed.data[index];
  23032. if (data) {
  23033. data.dispose();
  23034. }
  23035. this._toBeDisposed[index] = null;
  23036. }
  23037. this._toBeDisposed.reset();
  23038. if (this.dumpNextRenderTargets) {
  23039. this.dumpNextRenderTargets = false;
  23040. }
  23041. this._activeBones.addCount(0, true);
  23042. this._activeIndices.addCount(0, true);
  23043. this._activeParticles.addCount(0, true);
  23044. };
  23045. Scene.prototype._updateAudioParameters = function () {
  23046. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23047. return;
  23048. }
  23049. var listeningCamera;
  23050. var audioEngine = BABYLON.Engine.audioEngine;
  23051. if (this.activeCameras.length > 0) {
  23052. listeningCamera = this.activeCameras[0];
  23053. }
  23054. else {
  23055. listeningCamera = this.activeCamera;
  23056. }
  23057. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23058. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23059. // for VR cameras
  23060. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23061. listeningCamera = listeningCamera.rigCameras[0];
  23062. }
  23063. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23064. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23065. cameraDirection.normalize();
  23066. // To avoid some errors on GearVR
  23067. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23068. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23069. }
  23070. var i;
  23071. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23072. var sound = this.mainSoundTrack.soundCollection[i];
  23073. if (sound.useCustomAttenuation) {
  23074. sound.updateDistanceFromListener();
  23075. }
  23076. }
  23077. for (i = 0; i < this.soundTracks.length; i++) {
  23078. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23079. sound = this.soundTracks[i].soundCollection[j];
  23080. if (sound.useCustomAttenuation) {
  23081. sound.updateDistanceFromListener();
  23082. }
  23083. }
  23084. }
  23085. }
  23086. };
  23087. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23088. // Audio
  23089. get: function () {
  23090. return this._audioEnabled;
  23091. },
  23092. set: function (value) {
  23093. this._audioEnabled = value;
  23094. if (BABYLON.AudioEngine) {
  23095. if (this._audioEnabled) {
  23096. this._enableAudio();
  23097. }
  23098. else {
  23099. this._disableAudio();
  23100. }
  23101. }
  23102. },
  23103. enumerable: true,
  23104. configurable: true
  23105. });
  23106. Scene.prototype._disableAudio = function () {
  23107. var i;
  23108. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23109. this.mainSoundTrack.soundCollection[i].pause();
  23110. }
  23111. for (i = 0; i < this.soundTracks.length; i++) {
  23112. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23113. this.soundTracks[i].soundCollection[j].pause();
  23114. }
  23115. }
  23116. };
  23117. Scene.prototype._enableAudio = function () {
  23118. var i;
  23119. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23120. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23121. this.mainSoundTrack.soundCollection[i].play();
  23122. }
  23123. }
  23124. for (i = 0; i < this.soundTracks.length; i++) {
  23125. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23126. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23127. this.soundTracks[i].soundCollection[j].play();
  23128. }
  23129. }
  23130. }
  23131. };
  23132. Object.defineProperty(Scene.prototype, "headphone", {
  23133. get: function () {
  23134. return this._headphone;
  23135. },
  23136. set: function (value) {
  23137. this._headphone = value;
  23138. if (BABYLON.AudioEngine) {
  23139. if (this._headphone) {
  23140. this._switchAudioModeForHeadphones();
  23141. }
  23142. else {
  23143. this._switchAudioModeForNormalSpeakers();
  23144. }
  23145. }
  23146. },
  23147. enumerable: true,
  23148. configurable: true
  23149. });
  23150. Scene.prototype._switchAudioModeForHeadphones = function () {
  23151. this.mainSoundTrack.switchPanningModelToHRTF();
  23152. for (var i = 0; i < this.soundTracks.length; i++) {
  23153. this.soundTracks[i].switchPanningModelToHRTF();
  23154. }
  23155. };
  23156. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23157. this.mainSoundTrack.switchPanningModelToEqualPower();
  23158. for (var i = 0; i < this.soundTracks.length; i++) {
  23159. this.soundTracks[i].switchPanningModelToEqualPower();
  23160. }
  23161. };
  23162. Scene.prototype.enableDepthRenderer = function () {
  23163. if (this._depthRenderer) {
  23164. return this._depthRenderer;
  23165. }
  23166. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23167. return this._depthRenderer;
  23168. };
  23169. Scene.prototype.disableDepthRenderer = function () {
  23170. if (!this._depthRenderer) {
  23171. return;
  23172. }
  23173. this._depthRenderer.dispose();
  23174. this._depthRenderer = null;
  23175. };
  23176. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23177. if (ratio === void 0) { ratio = 1; }
  23178. if (this._geometryBufferRenderer) {
  23179. return this._geometryBufferRenderer;
  23180. }
  23181. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23182. if (!this._geometryBufferRenderer.isSupported) {
  23183. this._geometryBufferRenderer = null;
  23184. }
  23185. return this._geometryBufferRenderer;
  23186. };
  23187. Scene.prototype.disableGeometryBufferRenderer = function () {
  23188. if (!this._geometryBufferRenderer) {
  23189. return;
  23190. }
  23191. this._geometryBufferRenderer.dispose();
  23192. this._geometryBufferRenderer = null;
  23193. };
  23194. Scene.prototype.freezeMaterials = function () {
  23195. for (var i = 0; i < this.materials.length; i++) {
  23196. this.materials[i].freeze();
  23197. }
  23198. };
  23199. Scene.prototype.unfreezeMaterials = function () {
  23200. for (var i = 0; i < this.materials.length; i++) {
  23201. this.materials[i].unfreeze();
  23202. }
  23203. };
  23204. Scene.prototype.dispose = function () {
  23205. this.beforeRender = null;
  23206. this.afterRender = null;
  23207. this.skeletons = [];
  23208. this.morphTargetManagers = [];
  23209. this.importedMeshesFiles = new Array();
  23210. this.stopAllAnimations();
  23211. this.resetCachedMaterial();
  23212. if (this._depthRenderer) {
  23213. this._depthRenderer.dispose();
  23214. }
  23215. if (this._gamepadManager) {
  23216. this._gamepadManager.dispose();
  23217. this._gamepadManager = null;
  23218. }
  23219. // Smart arrays
  23220. if (this.activeCamera) {
  23221. this.activeCamera._activeMeshes.dispose();
  23222. this.activeCamera = null;
  23223. }
  23224. this._activeMeshes.dispose();
  23225. this._renderingManager.dispose();
  23226. this._processedMaterials.dispose();
  23227. this._activeParticleSystems.dispose();
  23228. this._activeSkeletons.dispose();
  23229. this._softwareSkinnedMeshes.dispose();
  23230. this._renderTargets.dispose();
  23231. if (this._boundingBoxRenderer) {
  23232. this._boundingBoxRenderer.dispose();
  23233. }
  23234. this._meshesForIntersections.dispose();
  23235. this._toBeDisposed.dispose();
  23236. // Abort active requests
  23237. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23238. var request = _a[_i];
  23239. request.abort();
  23240. }
  23241. // Debug layer
  23242. if (this._debugLayer) {
  23243. this._debugLayer.hide();
  23244. }
  23245. // Events
  23246. this.onDisposeObservable.notifyObservers(this);
  23247. this.onDisposeObservable.clear();
  23248. this.onBeforeRenderObservable.clear();
  23249. this.onAfterRenderObservable.clear();
  23250. this.OnBeforeRenderTargetsRenderObservable.clear();
  23251. this.OnAfterRenderTargetsRenderObservable.clear();
  23252. this.onAfterStepObservable.clear();
  23253. this.onBeforeStepObservable.clear();
  23254. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23255. this.onAfterActiveMeshesEvaluationObservable.clear();
  23256. this.onBeforeParticlesRenderingObservable.clear();
  23257. this.onAfterParticlesRenderingObservable.clear();
  23258. this.onBeforeSpritesRenderingObservable.clear();
  23259. this.onAfterSpritesRenderingObservable.clear();
  23260. this.onBeforeDrawPhaseObservable.clear();
  23261. this.onAfterDrawPhaseObservable.clear();
  23262. this.onBeforePhysicsObservable.clear();
  23263. this.onAfterPhysicsObservable.clear();
  23264. this.onBeforeAnimationsObservable.clear();
  23265. this.onAfterAnimationsObservable.clear();
  23266. this.onDataLoadedObservable.clear();
  23267. this.detachControl();
  23268. // Release sounds & sounds tracks
  23269. if (BABYLON.AudioEngine) {
  23270. this.disposeSounds();
  23271. }
  23272. // VR Helper
  23273. if (this.VRHelper) {
  23274. this.VRHelper.dispose();
  23275. }
  23276. // Detach cameras
  23277. var canvas = this._engine.getRenderingCanvas();
  23278. if (canvas) {
  23279. var index;
  23280. for (index = 0; index < this.cameras.length; index++) {
  23281. this.cameras[index].detachControl(canvas);
  23282. }
  23283. }
  23284. // Release animation groups
  23285. while (this.animationGroups.length) {
  23286. this.animationGroups[0].dispose();
  23287. }
  23288. // Release lights
  23289. while (this.lights.length) {
  23290. this.lights[0].dispose();
  23291. }
  23292. // Release meshes
  23293. while (this.meshes.length) {
  23294. this.meshes[0].dispose(true);
  23295. }
  23296. while (this.transformNodes.length) {
  23297. this.removeTransformNode(this.transformNodes[0]);
  23298. }
  23299. // Release cameras
  23300. while (this.cameras.length) {
  23301. this.cameras[0].dispose();
  23302. }
  23303. // Release materials
  23304. if (this.defaultMaterial) {
  23305. this.defaultMaterial.dispose();
  23306. }
  23307. while (this.multiMaterials.length) {
  23308. this.multiMaterials[0].dispose();
  23309. }
  23310. while (this.materials.length) {
  23311. this.materials[0].dispose();
  23312. }
  23313. // Release particles
  23314. while (this.particleSystems.length) {
  23315. this.particleSystems[0].dispose();
  23316. }
  23317. // Release sprites
  23318. while (this.spriteManagers.length) {
  23319. this.spriteManagers[0].dispose();
  23320. }
  23321. // Release postProcesses
  23322. while (this.postProcesses.length) {
  23323. this.postProcesses[0].dispose();
  23324. }
  23325. // Release layers
  23326. while (this.layers.length) {
  23327. this.layers[0].dispose();
  23328. }
  23329. while (this.highlightLayers.length) {
  23330. this.highlightLayers[0].dispose();
  23331. }
  23332. // Release textures
  23333. while (this.textures.length) {
  23334. this.textures[0].dispose();
  23335. }
  23336. // Release UBO
  23337. this._sceneUbo.dispose();
  23338. if (this._alternateSceneUbo) {
  23339. this._alternateSceneUbo.dispose();
  23340. }
  23341. // Post-processes
  23342. this.postProcessManager.dispose();
  23343. if (this._postProcessRenderPipelineManager) {
  23344. this._postProcessRenderPipelineManager.dispose();
  23345. }
  23346. // Physics
  23347. if (this._physicsEngine) {
  23348. this.disablePhysicsEngine();
  23349. }
  23350. // Remove from engine
  23351. index = this._engine.scenes.indexOf(this);
  23352. if (index > -1) {
  23353. this._engine.scenes.splice(index, 1);
  23354. }
  23355. this._engine.wipeCaches(true);
  23356. this._isDisposed = true;
  23357. };
  23358. Object.defineProperty(Scene.prototype, "isDisposed", {
  23359. get: function () {
  23360. return this._isDisposed;
  23361. },
  23362. enumerable: true,
  23363. configurable: true
  23364. });
  23365. // Release sounds & sounds tracks
  23366. Scene.prototype.disposeSounds = function () {
  23367. if (!this._mainSoundTrack) {
  23368. return;
  23369. }
  23370. this.mainSoundTrack.dispose();
  23371. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23372. this.soundTracks[scIndex].dispose();
  23373. }
  23374. };
  23375. // Octrees
  23376. Scene.prototype.getWorldExtends = function () {
  23377. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23378. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23379. for (var index = 0; index < this.meshes.length; index++) {
  23380. var mesh = this.meshes[index];
  23381. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23382. continue;
  23383. }
  23384. mesh.computeWorldMatrix(true);
  23385. var boundingInfo = mesh.getBoundingInfo();
  23386. var minBox = boundingInfo.boundingBox.minimumWorld;
  23387. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23388. BABYLON.Tools.CheckExtends(minBox, min, max);
  23389. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23390. }
  23391. return {
  23392. min: min,
  23393. max: max
  23394. };
  23395. };
  23396. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23397. if (maxCapacity === void 0) { maxCapacity = 64; }
  23398. if (maxDepth === void 0) { maxDepth = 2; }
  23399. if (!this._selectionOctree) {
  23400. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23401. }
  23402. var worldExtends = this.getWorldExtends();
  23403. // Update octree
  23404. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23405. return this._selectionOctree;
  23406. };
  23407. // Picking
  23408. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23409. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23410. var result = BABYLON.Ray.Zero();
  23411. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23412. return result;
  23413. };
  23414. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23415. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23416. var engine = this._engine;
  23417. if (!camera) {
  23418. if (!this.activeCamera)
  23419. throw new Error("Active camera not set");
  23420. camera = this.activeCamera;
  23421. }
  23422. var cameraViewport = camera.viewport;
  23423. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23424. // Moving coordinates to local viewport world
  23425. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23426. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23427. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23428. return this;
  23429. };
  23430. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23431. var result = BABYLON.Ray.Zero();
  23432. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23433. return result;
  23434. };
  23435. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23436. if (!BABYLON.PickingInfo) {
  23437. return this;
  23438. }
  23439. var engine = this._engine;
  23440. if (!camera) {
  23441. if (!this.activeCamera)
  23442. throw new Error("Active camera not set");
  23443. camera = this.activeCamera;
  23444. }
  23445. var cameraViewport = camera.viewport;
  23446. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23447. var identity = BABYLON.Matrix.Identity();
  23448. // Moving coordinates to local viewport world
  23449. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23450. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23451. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23452. return this;
  23453. };
  23454. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23455. if (!BABYLON.PickingInfo) {
  23456. return null;
  23457. }
  23458. var pickingInfo = null;
  23459. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23460. var mesh = this.meshes[meshIndex];
  23461. if (predicate) {
  23462. if (!predicate(mesh)) {
  23463. continue;
  23464. }
  23465. }
  23466. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23467. continue;
  23468. }
  23469. var world = mesh.getWorldMatrix();
  23470. var ray = rayFunction(world);
  23471. var result = mesh.intersects(ray, fastCheck);
  23472. if (!result || !result.hit)
  23473. continue;
  23474. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23475. continue;
  23476. pickingInfo = result;
  23477. if (fastCheck) {
  23478. break;
  23479. }
  23480. }
  23481. return pickingInfo || new BABYLON.PickingInfo();
  23482. };
  23483. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23484. if (!BABYLON.PickingInfo) {
  23485. return null;
  23486. }
  23487. var pickingInfos = new Array();
  23488. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23489. var mesh = this.meshes[meshIndex];
  23490. if (predicate) {
  23491. if (!predicate(mesh)) {
  23492. continue;
  23493. }
  23494. }
  23495. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23496. continue;
  23497. }
  23498. var world = mesh.getWorldMatrix();
  23499. var ray = rayFunction(world);
  23500. var result = mesh.intersects(ray, false);
  23501. if (!result || !result.hit)
  23502. continue;
  23503. pickingInfos.push(result);
  23504. }
  23505. return pickingInfos;
  23506. };
  23507. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23508. if (!BABYLON.PickingInfo) {
  23509. return null;
  23510. }
  23511. var pickingInfo = null;
  23512. if (!camera) {
  23513. if (!this.activeCamera) {
  23514. return null;
  23515. }
  23516. camera = this.activeCamera;
  23517. }
  23518. if (this.spriteManagers.length > 0) {
  23519. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23520. var spriteManager = this.spriteManagers[spriteIndex];
  23521. if (!spriteManager.isPickable) {
  23522. continue;
  23523. }
  23524. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23525. if (!result || !result.hit)
  23526. continue;
  23527. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23528. continue;
  23529. pickingInfo = result;
  23530. if (fastCheck) {
  23531. break;
  23532. }
  23533. }
  23534. }
  23535. return pickingInfo || new BABYLON.PickingInfo();
  23536. };
  23537. /** Launch a ray to try to pick a mesh in the scene
  23538. * @param x position on screen
  23539. * @param y position on screen
  23540. * @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
  23541. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23542. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23543. */
  23544. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23545. var _this = this;
  23546. if (!BABYLON.PickingInfo) {
  23547. return null;
  23548. }
  23549. return this._internalPick(function (world) {
  23550. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23551. return _this._tempPickingRay;
  23552. }, predicate, fastCheck);
  23553. };
  23554. /** Launch a ray to try to pick a sprite in the scene
  23555. * @param x position on screen
  23556. * @param y position on screen
  23557. * @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
  23558. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23559. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23560. */
  23561. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23562. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23563. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23564. };
  23565. /** Use the given ray to pick a mesh in the scene
  23566. * @param ray The ray to use to pick meshes
  23567. * @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
  23568. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23569. */
  23570. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23571. var _this = this;
  23572. return this._internalPick(function (world) {
  23573. if (!_this._pickWithRayInverseMatrix) {
  23574. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23575. }
  23576. world.invertToRef(_this._pickWithRayInverseMatrix);
  23577. if (!_this._cachedRayForTransform) {
  23578. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23579. }
  23580. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23581. return _this._cachedRayForTransform;
  23582. }, predicate, fastCheck);
  23583. };
  23584. /**
  23585. * Launch a ray to try to pick a mesh in the scene
  23586. * @param x X position on screen
  23587. * @param y Y position on screen
  23588. * @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
  23589. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23590. */
  23591. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23592. var _this = this;
  23593. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23594. };
  23595. /**
  23596. * Launch a ray to try to pick a mesh in the scene
  23597. * @param ray Ray to use
  23598. * @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
  23599. */
  23600. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23601. var _this = this;
  23602. return this._internalMultiPick(function (world) {
  23603. if (!_this._pickWithRayInverseMatrix) {
  23604. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23605. }
  23606. world.invertToRef(_this._pickWithRayInverseMatrix);
  23607. if (!_this._cachedRayForTransform) {
  23608. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23609. }
  23610. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23611. return _this._cachedRayForTransform;
  23612. }, predicate);
  23613. };
  23614. Scene.prototype.setPointerOverMesh = function (mesh) {
  23615. if (this._pointerOverMesh === mesh) {
  23616. return;
  23617. }
  23618. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23619. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23620. }
  23621. this._pointerOverMesh = mesh;
  23622. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23623. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23624. }
  23625. };
  23626. Scene.prototype.getPointerOverMesh = function () {
  23627. return this._pointerOverMesh;
  23628. };
  23629. Scene.prototype.setPointerOverSprite = function (sprite) {
  23630. if (this._pointerOverSprite === sprite) {
  23631. return;
  23632. }
  23633. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23634. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23635. }
  23636. this._pointerOverSprite = sprite;
  23637. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23638. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23639. }
  23640. };
  23641. Scene.prototype.getPointerOverSprite = function () {
  23642. return this._pointerOverSprite;
  23643. };
  23644. // Physics
  23645. Scene.prototype.getPhysicsEngine = function () {
  23646. return this._physicsEngine;
  23647. };
  23648. /**
  23649. * Enables physics to the current scene
  23650. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23651. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23652. * @return {boolean} was the physics engine initialized
  23653. */
  23654. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23655. if (gravity === void 0) { gravity = null; }
  23656. if (this._physicsEngine) {
  23657. return true;
  23658. }
  23659. try {
  23660. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23661. return true;
  23662. }
  23663. catch (e) {
  23664. BABYLON.Tools.Error(e.message);
  23665. return false;
  23666. }
  23667. };
  23668. Scene.prototype.disablePhysicsEngine = function () {
  23669. if (!this._physicsEngine) {
  23670. return;
  23671. }
  23672. this._physicsEngine.dispose();
  23673. this._physicsEngine = null;
  23674. };
  23675. Scene.prototype.isPhysicsEnabled = function () {
  23676. return this._physicsEngine !== undefined;
  23677. };
  23678. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23679. var mesh = compound.parts[0].mesh;
  23680. if (mesh.physicsImpostor) {
  23681. mesh.physicsImpostor.dispose();
  23682. mesh.physicsImpostor = null;
  23683. }
  23684. };
  23685. // Misc.
  23686. Scene.prototype._rebuildGeometries = function () {
  23687. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23688. var geometry = _a[_i];
  23689. geometry._rebuild();
  23690. }
  23691. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23692. var mesh = _c[_b];
  23693. mesh._rebuild();
  23694. }
  23695. if (this.postProcessManager) {
  23696. this.postProcessManager._rebuild();
  23697. }
  23698. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23699. var layer = _e[_d];
  23700. layer._rebuild();
  23701. }
  23702. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23703. var highlightLayer = _g[_f];
  23704. highlightLayer._rebuild();
  23705. }
  23706. if (this._boundingBoxRenderer) {
  23707. this._boundingBoxRenderer._rebuild();
  23708. }
  23709. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23710. var system = _j[_h];
  23711. system.rebuild();
  23712. }
  23713. if (this._postProcessRenderPipelineManager) {
  23714. this._postProcessRenderPipelineManager._rebuild();
  23715. }
  23716. };
  23717. Scene.prototype._rebuildTextures = function () {
  23718. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23719. var texture = _a[_i];
  23720. texture._rebuild();
  23721. }
  23722. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23723. };
  23724. /**
  23725. * Creates a default light for the scene.
  23726. * @param replace Whether to replace the existing lights in the scene.
  23727. */
  23728. Scene.prototype.createDefaultLight = function (replace) {
  23729. if (replace === void 0) { replace = false; }
  23730. // Dispose existing light in replace mode.
  23731. if (replace) {
  23732. if (this.lights) {
  23733. for (var i = 0; i < this.lights.length; i++) {
  23734. this.lights[i].dispose();
  23735. }
  23736. }
  23737. }
  23738. // Light
  23739. if (this.lights.length === 0) {
  23740. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23741. }
  23742. };
  23743. /**
  23744. * Creates a default camera for the scene.
  23745. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  23746. * @param replace Whether to replace the existing active camera in the scene.
  23747. * @param attachCameraControls Whether to attach camera controls to the canvas.
  23748. */
  23749. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  23750. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23751. if (replace === void 0) { replace = false; }
  23752. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23753. // Dispose existing camera in replace mode.
  23754. if (replace) {
  23755. if (this.activeCamera) {
  23756. this.activeCamera.dispose();
  23757. this.activeCamera = null;
  23758. }
  23759. }
  23760. // Camera
  23761. if (!this.activeCamera) {
  23762. var worldExtends = this.getWorldExtends();
  23763. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23764. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23765. var camera;
  23766. var radius = worldSize.length() * 1.5;
  23767. if (createArcRotateCamera) {
  23768. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23769. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23770. arcRotateCamera.wheelPrecision = 100 / radius;
  23771. camera = arcRotateCamera;
  23772. }
  23773. else {
  23774. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23775. freeCamera.setTarget(worldCenter);
  23776. camera = freeCamera;
  23777. }
  23778. camera.minZ = radius * 0.01;
  23779. camera.maxZ = radius * 1000;
  23780. camera.speed = radius * 0.2;
  23781. this.activeCamera = camera;
  23782. var canvas = this.getEngine().getRenderingCanvas();
  23783. if (attachCameraControls && canvas) {
  23784. camera.attachControl(canvas);
  23785. }
  23786. }
  23787. };
  23788. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23789. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23790. if (replace === void 0) { replace = false; }
  23791. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23792. this.createDefaultLight(replace);
  23793. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  23794. };
  23795. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23796. if (pbr === void 0) { pbr = false; }
  23797. if (scale === void 0) { scale = 1000; }
  23798. if (blur === void 0) { blur = 0; }
  23799. if (environmentTexture) {
  23800. this.environmentTexture = environmentTexture;
  23801. }
  23802. if (!this.environmentTexture) {
  23803. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23804. return null;
  23805. }
  23806. // Skybox
  23807. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23808. if (pbr) {
  23809. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23810. hdrSkyboxMaterial.backFaceCulling = false;
  23811. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23812. if (hdrSkyboxMaterial.reflectionTexture) {
  23813. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23814. }
  23815. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23816. hdrSkyboxMaterial.disableLighting = true;
  23817. hdrSkyboxMaterial.twoSidedLighting = true;
  23818. hdrSkybox.infiniteDistance = true;
  23819. hdrSkybox.material = hdrSkyboxMaterial;
  23820. }
  23821. else {
  23822. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23823. skyboxMaterial.backFaceCulling = false;
  23824. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23825. if (skyboxMaterial.reflectionTexture) {
  23826. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23827. }
  23828. skyboxMaterial.disableLighting = true;
  23829. hdrSkybox.infiniteDistance = true;
  23830. hdrSkybox.material = skyboxMaterial;
  23831. }
  23832. return hdrSkybox;
  23833. };
  23834. Scene.prototype.createDefaultEnvironment = function (options) {
  23835. if (BABYLON.EnvironmentHelper) {
  23836. return new BABYLON.EnvironmentHelper(options, this);
  23837. }
  23838. return null;
  23839. };
  23840. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23841. if (webVROptions === void 0) { webVROptions = {}; }
  23842. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23843. };
  23844. // Tags
  23845. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23846. if (tagsQuery === undefined) {
  23847. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23848. return list;
  23849. }
  23850. var listByTags = [];
  23851. forEach = forEach || (function (item) { return; });
  23852. for (var i in list) {
  23853. var item = list[i];
  23854. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23855. listByTags.push(item);
  23856. forEach(item);
  23857. }
  23858. }
  23859. return listByTags;
  23860. };
  23861. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23862. return this._getByTags(this.meshes, tagsQuery, forEach);
  23863. };
  23864. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23865. return this._getByTags(this.cameras, tagsQuery, forEach);
  23866. };
  23867. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23868. return this._getByTags(this.lights, tagsQuery, forEach);
  23869. };
  23870. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23871. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23872. };
  23873. /**
  23874. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23875. * This allowed control for front to back rendering or reversly depending of the special needs.
  23876. *
  23877. * @param renderingGroupId The rendering group id corresponding to its index
  23878. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23879. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23880. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23881. */
  23882. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23883. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23884. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23885. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23886. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23887. };
  23888. /**
  23889. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23890. *
  23891. * @param renderingGroupId The rendering group id corresponding to its index
  23892. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23893. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23894. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23895. */
  23896. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23897. if (depth === void 0) { depth = true; }
  23898. if (stencil === void 0) { stencil = true; }
  23899. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23900. };
  23901. /**
  23902. * Will flag all materials as dirty to trigger new shader compilation
  23903. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23904. */
  23905. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23906. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23907. var material = _a[_i];
  23908. if (predicate && !predicate(material)) {
  23909. continue;
  23910. }
  23911. material.markAsDirty(flag);
  23912. }
  23913. };
  23914. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23915. var _this = this;
  23916. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23917. this._activeRequests.push(request);
  23918. request.onCompleteObservable.add(function (request) {
  23919. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23920. });
  23921. return request;
  23922. };
  23923. /** @ignore */
  23924. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  23925. var _this = this;
  23926. return new Promise(function (resolve, reject) {
  23927. _this._loadFile(url, function (data) {
  23928. resolve(data);
  23929. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  23930. reject(exception);
  23931. });
  23932. });
  23933. };
  23934. // Statics
  23935. Scene._FOGMODE_NONE = 0;
  23936. Scene._FOGMODE_EXP = 1;
  23937. Scene._FOGMODE_EXP2 = 2;
  23938. Scene._FOGMODE_LINEAR = 3;
  23939. Scene._uniqueIdCounter = 0;
  23940. Scene.MinDeltaTime = 1.0;
  23941. Scene.MaxDeltaTime = 1000.0;
  23942. /** The distance in pixel that you have to move to prevent some events */
  23943. Scene.DragMovementThreshold = 10; // in pixels
  23944. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23945. Scene.LongPressDelay = 500; // in milliseconds
  23946. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23947. Scene.DoubleClickDelay = 300; // in milliseconds
  23948. /** If you need to check double click without raising a single click at first click, enable this flag */
  23949. Scene.ExclusiveDoubleClickMode = false;
  23950. return Scene;
  23951. }());
  23952. BABYLON.Scene = Scene;
  23953. })(BABYLON || (BABYLON = {}));
  23954. //# sourceMappingURL=babylon.scene.js.map
  23955. var BABYLON;
  23956. (function (BABYLON) {
  23957. /**
  23958. * Set of assets to keep when moving a scene into an asset container.
  23959. */
  23960. var KeepAssets = /** @class */ (function () {
  23961. function KeepAssets() {
  23962. /**
  23963. * Cameras to keep.
  23964. */
  23965. this.cameras = new Array();
  23966. /**
  23967. * Lights to keep.
  23968. */
  23969. this.lights = new Array();
  23970. /**
  23971. * Meshes to keep.
  23972. */
  23973. this.meshes = new Array();
  23974. /**
  23975. * Skeletons to keep.
  23976. */
  23977. this.skeletons = new Array();
  23978. /**
  23979. * ParticleSystems to keep.
  23980. */
  23981. this.particleSystems = new Array();
  23982. /**
  23983. * Animations to keep.
  23984. */
  23985. this.animations = new Array();
  23986. /**
  23987. * MultiMaterials to keep.
  23988. */
  23989. this.multiMaterials = new Array();
  23990. /**
  23991. * Materials to keep.
  23992. */
  23993. this.materials = new Array();
  23994. /**
  23995. * MorphTargetManagers to keep.
  23996. */
  23997. this.morphTargetManagers = new Array();
  23998. /**
  23999. * Geometries to keep.
  24000. */
  24001. this.geometries = new Array();
  24002. /**
  24003. * TransformNodes to keep.
  24004. */
  24005. this.transformNodes = new Array();
  24006. /**
  24007. * LensFlareSystems to keep.
  24008. */
  24009. this.lensFlareSystems = new Array();
  24010. /**
  24011. * ShadowGenerators to keep.
  24012. */
  24013. this.shadowGenerators = new Array();
  24014. /**
  24015. * ActionManagers to keep.
  24016. */
  24017. this.actionManagers = new Array();
  24018. /**
  24019. * Sounds to keep.
  24020. */
  24021. this.sounds = new Array();
  24022. }
  24023. return KeepAssets;
  24024. }());
  24025. BABYLON.KeepAssets = KeepAssets;
  24026. /**
  24027. * Container with a set of assets that can be added or removed from a scene.
  24028. */
  24029. var AssetContainer = /** @class */ (function () {
  24030. /**
  24031. * Instantiates an AssetContainer.
  24032. * @param scene The scene the AssetContainer belongs to.
  24033. */
  24034. function AssetContainer(scene) {
  24035. // Objects
  24036. /**
  24037. * Cameras populated in the container.
  24038. */
  24039. this.cameras = new Array();
  24040. /**
  24041. * Lights populated in the container.
  24042. */
  24043. this.lights = new Array();
  24044. /**
  24045. * Meshes populated in the container.
  24046. */
  24047. this.meshes = new Array();
  24048. /**
  24049. * Skeletons populated in the container.
  24050. */
  24051. this.skeletons = new Array();
  24052. /**
  24053. * ParticleSystems populated in the container.
  24054. */
  24055. this.particleSystems = new Array();
  24056. /**
  24057. * Animations populated in the container.
  24058. */
  24059. this.animations = new Array();
  24060. /**
  24061. * MultiMaterials populated in the container.
  24062. */
  24063. this.multiMaterials = new Array();
  24064. /**
  24065. * Materials populated in the container.
  24066. */
  24067. this.materials = new Array();
  24068. /**
  24069. * MorphTargetManagers populated in the container.
  24070. */
  24071. this.morphTargetManagers = new Array();
  24072. /**
  24073. * Geometries populated in the container.
  24074. */
  24075. this.geometries = new Array();
  24076. /**
  24077. * TransformNodes populated in the container.
  24078. */
  24079. this.transformNodes = new Array();
  24080. /**
  24081. * LensFlareSystems populated in the container.
  24082. */
  24083. this.lensFlareSystems = new Array();
  24084. /**
  24085. * ShadowGenerators populated in the container.
  24086. */
  24087. this.shadowGenerators = new Array();
  24088. /**
  24089. * ActionManagers populated in the container.
  24090. */
  24091. this.actionManagers = new Array();
  24092. /**
  24093. * Sounds populated in the container.
  24094. */
  24095. this.sounds = new Array();
  24096. this.scene = scene;
  24097. }
  24098. /**
  24099. * Adds all the assets from the container to the scene.
  24100. */
  24101. AssetContainer.prototype.addAllToScene = function () {
  24102. var _this = this;
  24103. this.cameras.forEach(function (o) {
  24104. _this.scene.addCamera(o);
  24105. });
  24106. this.lights.forEach(function (o) {
  24107. _this.scene.addLight(o);
  24108. });
  24109. this.meshes.forEach(function (o) {
  24110. _this.scene.addMesh(o);
  24111. });
  24112. this.skeletons.forEach(function (o) {
  24113. _this.scene.addSkeleton(o);
  24114. });
  24115. this.particleSystems.forEach(function (o) {
  24116. _this.scene.addParticleSystem(o);
  24117. });
  24118. this.animations.forEach(function (o) {
  24119. _this.scene.addAnimation(o);
  24120. });
  24121. this.multiMaterials.forEach(function (o) {
  24122. _this.scene.addMultiMaterial(o);
  24123. });
  24124. this.materials.forEach(function (o) {
  24125. _this.scene.addMaterial(o);
  24126. });
  24127. this.morphTargetManagers.forEach(function (o) {
  24128. _this.scene.addMorphTargetManager(o);
  24129. });
  24130. this.geometries.forEach(function (o) {
  24131. _this.scene.addGeometry(o);
  24132. });
  24133. this.transformNodes.forEach(function (o) {
  24134. _this.scene.addTransformNode(o);
  24135. });
  24136. this.lensFlareSystems.forEach(function (o) {
  24137. _this.scene.addLensFlareSystem(o);
  24138. });
  24139. this.actionManagers.forEach(function (o) {
  24140. _this.scene.addActionManager(o);
  24141. });
  24142. this.sounds.forEach(function (o) {
  24143. o.play();
  24144. o.autoplay = true;
  24145. _this.scene.mainSoundTrack.AddSound(o);
  24146. });
  24147. };
  24148. /**
  24149. * Removes all the assets in the container from the scene
  24150. */
  24151. AssetContainer.prototype.removeAllFromScene = function () {
  24152. var _this = this;
  24153. this.cameras.forEach(function (o) {
  24154. _this.scene.removeCamera(o);
  24155. });
  24156. this.lights.forEach(function (o) {
  24157. _this.scene.removeLight(o);
  24158. });
  24159. this.meshes.forEach(function (o) {
  24160. _this.scene.removeMesh(o);
  24161. });
  24162. this.skeletons.forEach(function (o) {
  24163. _this.scene.removeSkeleton(o);
  24164. });
  24165. this.particleSystems.forEach(function (o) {
  24166. _this.scene.removeParticleSystem(o);
  24167. });
  24168. this.animations.forEach(function (o) {
  24169. _this.scene.removeAnimation(o);
  24170. });
  24171. this.multiMaterials.forEach(function (o) {
  24172. _this.scene.removeMultiMaterial(o);
  24173. });
  24174. this.materials.forEach(function (o) {
  24175. _this.scene.removeMaterial(o);
  24176. });
  24177. this.morphTargetManagers.forEach(function (o) {
  24178. _this.scene.removeMorphTargetManager(o);
  24179. });
  24180. this.geometries.forEach(function (o) {
  24181. _this.scene.removeGeometry(o);
  24182. });
  24183. this.transformNodes.forEach(function (o) {
  24184. _this.scene.removeTransformNode(o);
  24185. });
  24186. this.lensFlareSystems.forEach(function (o) {
  24187. _this.scene.removeLensFlareSystem(o);
  24188. });
  24189. this.actionManagers.forEach(function (o) {
  24190. _this.scene.removeActionManager(o);
  24191. });
  24192. this.sounds.forEach(function (o) {
  24193. o.stop();
  24194. o.autoplay = false;
  24195. _this.scene.mainSoundTrack.RemoveSound(o);
  24196. });
  24197. };
  24198. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24199. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24200. var asset = sourceAssets_1[_i];
  24201. var move = true;
  24202. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24203. var keepAsset = keepAssets_1[_a];
  24204. if (asset === keepAsset) {
  24205. move = false;
  24206. break;
  24207. }
  24208. }
  24209. if (move) {
  24210. targetAssets.push(asset);
  24211. }
  24212. }
  24213. };
  24214. /**
  24215. * Removes all the assets contained in the scene and adds them to the container.
  24216. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24217. */
  24218. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24219. if (keepAssets === undefined) {
  24220. keepAssets = new KeepAssets();
  24221. }
  24222. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24223. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24224. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24225. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24226. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  24227. Array.prototype.push.apply(this.animations, this.scene.animations);
  24228. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  24229. Array.prototype.push.apply(this.lights, this.scene.lights);
  24230. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  24231. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  24232. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  24233. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  24234. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  24235. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  24236. this.removeAllFromScene();
  24237. };
  24238. return AssetContainer;
  24239. }());
  24240. BABYLON.AssetContainer = AssetContainer;
  24241. })(BABYLON || (BABYLON = {}));
  24242. //# sourceMappingURL=babylon.assetContainer.js.map
  24243. var BABYLON;
  24244. (function (BABYLON) {
  24245. var Buffer = /** @class */ (function () {
  24246. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24247. if (instanced === void 0) { instanced = false; }
  24248. if (engine instanceof BABYLON.Mesh) {
  24249. this._engine = engine.getScene().getEngine();
  24250. }
  24251. else {
  24252. this._engine = engine;
  24253. }
  24254. this._updatable = updatable;
  24255. this._data = data;
  24256. this._strideSize = stride;
  24257. if (!postponeInternalCreation) {
  24258. this.create();
  24259. }
  24260. this._instanced = instanced;
  24261. this._instanceDivisor = instanced ? 1 : 0;
  24262. }
  24263. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24264. // a lot of these parameters are ignored as they are overriden by the buffer
  24265. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24266. };
  24267. // Properties
  24268. Buffer.prototype.isUpdatable = function () {
  24269. return this._updatable;
  24270. };
  24271. Buffer.prototype.getData = function () {
  24272. return this._data;
  24273. };
  24274. Buffer.prototype.getBuffer = function () {
  24275. return this._buffer;
  24276. };
  24277. Buffer.prototype.getStrideSize = function () {
  24278. return this._strideSize;
  24279. };
  24280. Buffer.prototype.getIsInstanced = function () {
  24281. return this._instanced;
  24282. };
  24283. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24284. get: function () {
  24285. return this._instanceDivisor;
  24286. },
  24287. set: function (value) {
  24288. this._instanceDivisor = value;
  24289. if (value == 0) {
  24290. this._instanced = false;
  24291. }
  24292. else {
  24293. this._instanced = true;
  24294. }
  24295. },
  24296. enumerable: true,
  24297. configurable: true
  24298. });
  24299. // Methods
  24300. Buffer.prototype.create = function (data) {
  24301. if (data === void 0) { data = null; }
  24302. if (!data && this._buffer) {
  24303. return; // nothing to do
  24304. }
  24305. data = data || this._data;
  24306. if (!data) {
  24307. return;
  24308. }
  24309. if (!this._buffer) {
  24310. if (this._updatable) {
  24311. this._buffer = this._engine.createDynamicVertexBuffer(data);
  24312. this._data = data;
  24313. }
  24314. else {
  24315. this._buffer = this._engine.createVertexBuffer(data);
  24316. }
  24317. }
  24318. else if (this._updatable) {
  24319. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  24320. this._data = data;
  24321. }
  24322. };
  24323. Buffer.prototype._rebuild = function () {
  24324. this._buffer = null;
  24325. this.create(this._data);
  24326. };
  24327. Buffer.prototype.update = function (data) {
  24328. this.create(data);
  24329. };
  24330. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  24331. if (!this._buffer) {
  24332. return;
  24333. }
  24334. if (this._updatable) {
  24335. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  24336. this._data = null;
  24337. }
  24338. };
  24339. Buffer.prototype.dispose = function () {
  24340. if (!this._buffer) {
  24341. return;
  24342. }
  24343. if (this._engine._releaseBuffer(this._buffer)) {
  24344. this._buffer = null;
  24345. }
  24346. };
  24347. return Buffer;
  24348. }());
  24349. BABYLON.Buffer = Buffer;
  24350. })(BABYLON || (BABYLON = {}));
  24351. //# sourceMappingURL=babylon.buffer.js.map
  24352. var BABYLON;
  24353. (function (BABYLON) {
  24354. var VertexBuffer = /** @class */ (function () {
  24355. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  24356. if (!stride) {
  24357. // Deduce stride from kind
  24358. switch (kind) {
  24359. case VertexBuffer.PositionKind:
  24360. stride = 3;
  24361. break;
  24362. case VertexBuffer.NormalKind:
  24363. stride = 3;
  24364. break;
  24365. case VertexBuffer.UVKind:
  24366. case VertexBuffer.UV2Kind:
  24367. case VertexBuffer.UV3Kind:
  24368. case VertexBuffer.UV4Kind:
  24369. case VertexBuffer.UV5Kind:
  24370. case VertexBuffer.UV6Kind:
  24371. stride = 2;
  24372. break;
  24373. case VertexBuffer.TangentKind:
  24374. case VertexBuffer.ColorKind:
  24375. stride = 4;
  24376. break;
  24377. case VertexBuffer.MatricesIndicesKind:
  24378. case VertexBuffer.MatricesIndicesExtraKind:
  24379. stride = 4;
  24380. break;
  24381. case VertexBuffer.MatricesWeightsKind:
  24382. case VertexBuffer.MatricesWeightsExtraKind:
  24383. default:
  24384. stride = 4;
  24385. break;
  24386. }
  24387. }
  24388. if (data instanceof BABYLON.Buffer) {
  24389. if (!stride) {
  24390. stride = data.getStrideSize();
  24391. }
  24392. this._buffer = data;
  24393. this._ownsBuffer = false;
  24394. }
  24395. else {
  24396. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24397. this._ownsBuffer = true;
  24398. }
  24399. this._stride = stride;
  24400. this._offset = offset ? offset : 0;
  24401. this._size = size ? size : stride;
  24402. this._kind = kind;
  24403. }
  24404. VertexBuffer.prototype._rebuild = function () {
  24405. if (!this._buffer) {
  24406. return;
  24407. }
  24408. this._buffer._rebuild();
  24409. };
  24410. /**
  24411. * Returns the kind of the VertexBuffer (string).
  24412. */
  24413. VertexBuffer.prototype.getKind = function () {
  24414. return this._kind;
  24415. };
  24416. // Properties
  24417. /**
  24418. * Boolean : is the VertexBuffer updatable ?
  24419. */
  24420. VertexBuffer.prototype.isUpdatable = function () {
  24421. return this._buffer.isUpdatable();
  24422. };
  24423. /**
  24424. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24425. */
  24426. VertexBuffer.prototype.getData = function () {
  24427. return this._buffer.getData();
  24428. };
  24429. /**
  24430. * Returns the WebGLBuffer associated to the VertexBuffer.
  24431. */
  24432. VertexBuffer.prototype.getBuffer = function () {
  24433. return this._buffer.getBuffer();
  24434. };
  24435. /**
  24436. * Returns the stride of the VertexBuffer (integer).
  24437. */
  24438. VertexBuffer.prototype.getStrideSize = function () {
  24439. return this._stride;
  24440. };
  24441. /**
  24442. * Returns the offset (integer).
  24443. */
  24444. VertexBuffer.prototype.getOffset = function () {
  24445. return this._offset;
  24446. };
  24447. /**
  24448. * Returns the VertexBuffer total size (integer).
  24449. */
  24450. VertexBuffer.prototype.getSize = function () {
  24451. return this._size;
  24452. };
  24453. /**
  24454. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24455. */
  24456. VertexBuffer.prototype.getIsInstanced = function () {
  24457. return this._buffer.getIsInstanced();
  24458. };
  24459. /**
  24460. * Returns the instancing divisor, zero for non-instanced (integer).
  24461. */
  24462. VertexBuffer.prototype.getInstanceDivisor = function () {
  24463. return this._buffer.instanceDivisor;
  24464. };
  24465. // Methods
  24466. /**
  24467. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24468. * Returns the created WebGLBuffer.
  24469. */
  24470. VertexBuffer.prototype.create = function (data) {
  24471. return this._buffer.create(data);
  24472. };
  24473. /**
  24474. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24475. * This function will create a new buffer if the current one is not updatable
  24476. * Returns the updated WebGLBuffer.
  24477. */
  24478. VertexBuffer.prototype.update = function (data) {
  24479. return this._buffer.update(data);
  24480. };
  24481. /**
  24482. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24483. * Returns the directly updated WebGLBuffer.
  24484. */
  24485. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24486. return this._buffer.updateDirectly(data, offset);
  24487. };
  24488. /**
  24489. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24490. */
  24491. VertexBuffer.prototype.dispose = function () {
  24492. if (this._ownsBuffer) {
  24493. this._buffer.dispose();
  24494. }
  24495. };
  24496. Object.defineProperty(VertexBuffer, "PositionKind", {
  24497. get: function () {
  24498. return VertexBuffer._PositionKind;
  24499. },
  24500. enumerable: true,
  24501. configurable: true
  24502. });
  24503. Object.defineProperty(VertexBuffer, "NormalKind", {
  24504. get: function () {
  24505. return VertexBuffer._NormalKind;
  24506. },
  24507. enumerable: true,
  24508. configurable: true
  24509. });
  24510. Object.defineProperty(VertexBuffer, "TangentKind", {
  24511. get: function () {
  24512. return VertexBuffer._TangentKind;
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. Object.defineProperty(VertexBuffer, "UVKind", {
  24518. get: function () {
  24519. return VertexBuffer._UVKind;
  24520. },
  24521. enumerable: true,
  24522. configurable: true
  24523. });
  24524. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24525. get: function () {
  24526. return VertexBuffer._UV2Kind;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24532. get: function () {
  24533. return VertexBuffer._UV3Kind;
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24539. get: function () {
  24540. return VertexBuffer._UV4Kind;
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24546. get: function () {
  24547. return VertexBuffer._UV5Kind;
  24548. },
  24549. enumerable: true,
  24550. configurable: true
  24551. });
  24552. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24553. get: function () {
  24554. return VertexBuffer._UV6Kind;
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(VertexBuffer, "ColorKind", {
  24560. get: function () {
  24561. return VertexBuffer._ColorKind;
  24562. },
  24563. enumerable: true,
  24564. configurable: true
  24565. });
  24566. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24567. get: function () {
  24568. return VertexBuffer._MatricesIndicesKind;
  24569. },
  24570. enumerable: true,
  24571. configurable: true
  24572. });
  24573. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24574. get: function () {
  24575. return VertexBuffer._MatricesWeightsKind;
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24581. get: function () {
  24582. return VertexBuffer._MatricesIndicesExtraKind;
  24583. },
  24584. enumerable: true,
  24585. configurable: true
  24586. });
  24587. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24588. get: function () {
  24589. return VertexBuffer._MatricesWeightsExtraKind;
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. // Enums
  24595. VertexBuffer._PositionKind = "position";
  24596. VertexBuffer._NormalKind = "normal";
  24597. VertexBuffer._TangentKind = "tangent";
  24598. VertexBuffer._UVKind = "uv";
  24599. VertexBuffer._UV2Kind = "uv2";
  24600. VertexBuffer._UV3Kind = "uv3";
  24601. VertexBuffer._UV4Kind = "uv4";
  24602. VertexBuffer._UV5Kind = "uv5";
  24603. VertexBuffer._UV6Kind = "uv6";
  24604. VertexBuffer._ColorKind = "color";
  24605. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24606. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24607. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24608. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24609. return VertexBuffer;
  24610. }());
  24611. BABYLON.VertexBuffer = VertexBuffer;
  24612. })(BABYLON || (BABYLON = {}));
  24613. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24614. var BABYLON;
  24615. (function (BABYLON) {
  24616. /**
  24617. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24618. */
  24619. var DummyInternalTextureTracker = /** @class */ (function () {
  24620. function DummyInternalTextureTracker() {
  24621. /**
  24622. * Gets or set the previous tracker in the list
  24623. */
  24624. this.previous = null;
  24625. /**
  24626. * Gets or set the next tracker in the list
  24627. */
  24628. this.next = null;
  24629. }
  24630. return DummyInternalTextureTracker;
  24631. }());
  24632. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24633. })(BABYLON || (BABYLON = {}));
  24634. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24635. var BABYLON;
  24636. (function (BABYLON) {
  24637. /**
  24638. * Class used to store data associated with WebGL texture data for the engine
  24639. * This class should not be used directly
  24640. */
  24641. var InternalTexture = /** @class */ (function () {
  24642. /**
  24643. * Creates a new InternalTexture
  24644. * @param engine defines the engine to use
  24645. * @param dataSource defines the type of data that will be used
  24646. */
  24647. function InternalTexture(engine, dataSource) {
  24648. /**
  24649. * Observable called when the texture is loaded
  24650. */
  24651. this.onLoadedObservable = new BABYLON.Observable();
  24652. /**
  24653. * Gets or set the previous tracker in the list
  24654. */
  24655. this.previous = null;
  24656. /**
  24657. * Gets or set the next tracker in the list
  24658. */
  24659. this.next = null;
  24660. // Private
  24661. /** @ignore */
  24662. this._initialSlot = -1;
  24663. /** @ignore */
  24664. this._designatedSlot = -1;
  24665. /** @ignore */
  24666. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24667. /** @ignore */
  24668. this._references = 1;
  24669. this._engine = engine;
  24670. this._dataSource = dataSource;
  24671. this._webGLTexture = engine._createTexture();
  24672. }
  24673. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24674. /**
  24675. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24676. */
  24677. get: function () {
  24678. return this._dataSource;
  24679. },
  24680. enumerable: true,
  24681. configurable: true
  24682. });
  24683. /**
  24684. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24685. */
  24686. InternalTexture.prototype.incrementReferences = function () {
  24687. this._references++;
  24688. };
  24689. /**
  24690. * Change the size of the texture (not the size of the content)
  24691. * @param width defines the new width
  24692. * @param height defines the new height
  24693. * @param depth defines the new depth (1 by default)
  24694. */
  24695. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24696. if (depth === void 0) { depth = 1; }
  24697. this.width = width;
  24698. this.height = height;
  24699. this.depth = depth;
  24700. this.baseWidth = width;
  24701. this.baseHeight = height;
  24702. this.baseDepth = depth;
  24703. this._size = width * height * depth;
  24704. };
  24705. /** @ignore */
  24706. InternalTexture.prototype._rebuild = function () {
  24707. var _this = this;
  24708. var proxy;
  24709. this.isReady = false;
  24710. this._cachedCoordinatesMode = null;
  24711. this._cachedWrapU = null;
  24712. this._cachedWrapV = null;
  24713. this._cachedAnisotropicFilteringLevel = null;
  24714. switch (this._dataSource) {
  24715. case InternalTexture.DATASOURCE_TEMP:
  24716. return;
  24717. case InternalTexture.DATASOURCE_URL:
  24718. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24719. _this.isReady = true;
  24720. }, null, this._buffer, undefined, this.format);
  24721. proxy._swapAndDie(this);
  24722. return;
  24723. case InternalTexture.DATASOURCE_RAW:
  24724. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24725. proxy._swapAndDie(this);
  24726. this.isReady = true;
  24727. return;
  24728. case InternalTexture.DATASOURCE_RAW3D:
  24729. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24730. proxy._swapAndDie(this);
  24731. this.isReady = true;
  24732. return;
  24733. case InternalTexture.DATASOURCE_DYNAMIC:
  24734. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24735. proxy._swapAndDie(this);
  24736. // The engine will make sure to update content so no need to flag it as isReady = true
  24737. return;
  24738. case InternalTexture.DATASOURCE_RENDERTARGET:
  24739. var options = new BABYLON.RenderTargetCreationOptions();
  24740. options.generateDepthBuffer = this._generateDepthBuffer;
  24741. options.generateMipMaps = this.generateMipMaps;
  24742. options.generateStencilBuffer = this._generateStencilBuffer;
  24743. options.samplingMode = this.samplingMode;
  24744. options.type = this.type;
  24745. if (this.isCube) {
  24746. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24747. }
  24748. else {
  24749. var size = {
  24750. width: this.width,
  24751. height: this.height
  24752. };
  24753. proxy = this._engine.createRenderTargetTexture(size, options);
  24754. }
  24755. proxy._swapAndDie(this);
  24756. this.isReady = true;
  24757. return;
  24758. case InternalTexture.DATASOURCE_CUBE:
  24759. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24760. _this.isReady = true;
  24761. }, null, this.format, this._extension);
  24762. proxy._swapAndDie(this);
  24763. return;
  24764. case InternalTexture.DATASOURCE_CUBERAW:
  24765. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24766. proxy._swapAndDie(this);
  24767. this.isReady = true;
  24768. return;
  24769. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24770. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24771. if (proxy) {
  24772. proxy._swapAndDie(_this);
  24773. }
  24774. _this.isReady = true;
  24775. }, null, this.format, this._extension);
  24776. return;
  24777. }
  24778. };
  24779. InternalTexture.prototype._swapAndDie = function (target) {
  24780. target._webGLTexture = this._webGLTexture;
  24781. if (this._framebuffer) {
  24782. target._framebuffer = this._framebuffer;
  24783. }
  24784. if (this._depthStencilBuffer) {
  24785. target._depthStencilBuffer = this._depthStencilBuffer;
  24786. }
  24787. if (this._lodTextureHigh) {
  24788. if (target._lodTextureHigh) {
  24789. target._lodTextureHigh.dispose();
  24790. }
  24791. target._lodTextureHigh = this._lodTextureHigh;
  24792. }
  24793. if (this._lodTextureMid) {
  24794. if (target._lodTextureMid) {
  24795. target._lodTextureMid.dispose();
  24796. }
  24797. target._lodTextureMid = this._lodTextureMid;
  24798. }
  24799. if (this._lodTextureLow) {
  24800. if (target._lodTextureLow) {
  24801. target._lodTextureLow.dispose();
  24802. }
  24803. target._lodTextureLow = this._lodTextureLow;
  24804. }
  24805. var cache = this._engine.getLoadedTexturesCache();
  24806. var index = cache.indexOf(this);
  24807. if (index !== -1) {
  24808. cache.splice(index, 1);
  24809. }
  24810. };
  24811. /**
  24812. * Dispose the current allocated resources
  24813. */
  24814. InternalTexture.prototype.dispose = function () {
  24815. if (!this._webGLTexture) {
  24816. return;
  24817. }
  24818. this._references--;
  24819. if (this._references === 0) {
  24820. this._engine._releaseTexture(this);
  24821. this._webGLTexture = null;
  24822. this.previous = null;
  24823. this.next = null;
  24824. }
  24825. };
  24826. /**
  24827. * The source of the texture data is unknown
  24828. */
  24829. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24830. /**
  24831. * Texture data comes from an URL
  24832. */
  24833. InternalTexture.DATASOURCE_URL = 1;
  24834. /**
  24835. * Texture data is only used for temporary storage
  24836. */
  24837. InternalTexture.DATASOURCE_TEMP = 2;
  24838. /**
  24839. * Texture data comes from raw data (ArrayBuffer)
  24840. */
  24841. InternalTexture.DATASOURCE_RAW = 3;
  24842. /**
  24843. * Texture content is dynamic (video or dynamic texture)
  24844. */
  24845. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24846. /**
  24847. * Texture content is generated by rendering to it
  24848. */
  24849. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24850. /**
  24851. * Texture content is part of a multi render target process
  24852. */
  24853. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24854. /**
  24855. * Texture data comes from a cube data file
  24856. */
  24857. InternalTexture.DATASOURCE_CUBE = 7;
  24858. /**
  24859. * Texture data comes from a raw cube data
  24860. */
  24861. InternalTexture.DATASOURCE_CUBERAW = 8;
  24862. /**
  24863. * Texture data come from a prefiltered cube data file
  24864. */
  24865. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24866. /**
  24867. * Texture content is raw 3D data
  24868. */
  24869. InternalTexture.DATASOURCE_RAW3D = 10;
  24870. return InternalTexture;
  24871. }());
  24872. BABYLON.InternalTexture = InternalTexture;
  24873. })(BABYLON || (BABYLON = {}));
  24874. //# sourceMappingURL=babylon.internalTexture.js.map
  24875. var BABYLON;
  24876. (function (BABYLON) {
  24877. var BaseTexture = /** @class */ (function () {
  24878. function BaseTexture(scene) {
  24879. this._hasAlpha = false;
  24880. this.getAlphaFromRGB = false;
  24881. this.level = 1;
  24882. this.coordinatesIndex = 0;
  24883. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24884. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24885. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24886. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24887. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24888. this.isCube = false;
  24889. this.is3D = false;
  24890. this.gammaSpace = true;
  24891. this.invertZ = false;
  24892. this.lodLevelInAlpha = false;
  24893. this.lodGenerationOffset = 0.0;
  24894. this.lodGenerationScale = 0.8;
  24895. this.isRenderTarget = false;
  24896. this.animations = new Array();
  24897. /**
  24898. * An event triggered when the texture is disposed.
  24899. * @type {BABYLON.Observable}
  24900. */
  24901. this.onDisposeObservable = new BABYLON.Observable();
  24902. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24903. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24904. if (this._scene) {
  24905. this._scene.textures.push(this);
  24906. }
  24907. this._uid = null;
  24908. }
  24909. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24910. get: function () {
  24911. return this._hasAlpha;
  24912. },
  24913. set: function (value) {
  24914. if (this._hasAlpha === value) {
  24915. return;
  24916. }
  24917. this._hasAlpha = value;
  24918. if (this._scene) {
  24919. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  24920. }
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24926. get: function () {
  24927. return this._coordinatesMode;
  24928. },
  24929. set: function (value) {
  24930. if (this._coordinatesMode === value) {
  24931. return;
  24932. }
  24933. this._coordinatesMode = value;
  24934. if (this._scene) {
  24935. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24936. }
  24937. },
  24938. enumerable: true,
  24939. configurable: true
  24940. });
  24941. Object.defineProperty(BaseTexture.prototype, "uid", {
  24942. get: function () {
  24943. if (!this._uid) {
  24944. this._uid = BABYLON.Tools.RandomId();
  24945. }
  24946. return this._uid;
  24947. },
  24948. enumerable: true,
  24949. configurable: true
  24950. });
  24951. BaseTexture.prototype.toString = function () {
  24952. return this.name;
  24953. };
  24954. BaseTexture.prototype.getClassName = function () {
  24955. return "BaseTexture";
  24956. };
  24957. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24958. set: function (callback) {
  24959. if (this._onDisposeObserver) {
  24960. this.onDisposeObservable.remove(this._onDisposeObserver);
  24961. }
  24962. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24963. },
  24964. enumerable: true,
  24965. configurable: true
  24966. });
  24967. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24968. get: function () {
  24969. return true;
  24970. },
  24971. enumerable: true,
  24972. configurable: true
  24973. });
  24974. BaseTexture.prototype.getScene = function () {
  24975. return this._scene;
  24976. };
  24977. BaseTexture.prototype.getTextureMatrix = function () {
  24978. return BABYLON.Matrix.IdentityReadOnly;
  24979. };
  24980. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24981. return BABYLON.Matrix.IdentityReadOnly;
  24982. };
  24983. BaseTexture.prototype.getInternalTexture = function () {
  24984. return this._texture;
  24985. };
  24986. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24987. return !this.isBlocking || this.isReady();
  24988. };
  24989. BaseTexture.prototype.isReady = function () {
  24990. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24991. this.delayLoad();
  24992. return false;
  24993. }
  24994. if (this._texture) {
  24995. return this._texture.isReady;
  24996. }
  24997. return false;
  24998. };
  24999. BaseTexture.prototype.getSize = function () {
  25000. if (this._texture && this._texture.width) {
  25001. return new BABYLON.Size(this._texture.width, this._texture.height);
  25002. }
  25003. if (this._texture && this._texture._size) {
  25004. return new BABYLON.Size(this._texture._size, this._texture._size);
  25005. }
  25006. return BABYLON.Size.Zero();
  25007. };
  25008. BaseTexture.prototype.getBaseSize = function () {
  25009. if (!this.isReady() || !this._texture)
  25010. return BABYLON.Size.Zero();
  25011. if (this._texture._size) {
  25012. return new BABYLON.Size(this._texture._size, this._texture._size);
  25013. }
  25014. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25015. };
  25016. BaseTexture.prototype.scale = function (ratio) {
  25017. };
  25018. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25019. get: function () {
  25020. return false;
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25026. if (!this._scene) {
  25027. return null;
  25028. }
  25029. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25030. for (var index = 0; index < texturesCache.length; index++) {
  25031. var texturesCacheEntry = texturesCache[index];
  25032. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25033. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25034. texturesCacheEntry.incrementReferences();
  25035. return texturesCacheEntry;
  25036. }
  25037. }
  25038. }
  25039. return null;
  25040. };
  25041. BaseTexture.prototype._rebuild = function () {
  25042. };
  25043. BaseTexture.prototype.delayLoad = function () {
  25044. };
  25045. BaseTexture.prototype.clone = function () {
  25046. return null;
  25047. };
  25048. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25049. get: function () {
  25050. if (!this._texture) {
  25051. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25052. }
  25053. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25054. },
  25055. enumerable: true,
  25056. configurable: true
  25057. });
  25058. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25059. get: function () {
  25060. if (!this._texture) {
  25061. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25062. }
  25063. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25064. },
  25065. enumerable: true,
  25066. configurable: true
  25067. });
  25068. BaseTexture.prototype.readPixels = function (faceIndex) {
  25069. if (faceIndex === void 0) { faceIndex = 0; }
  25070. if (!this._texture) {
  25071. return null;
  25072. }
  25073. var size = this.getSize();
  25074. var scene = this.getScene();
  25075. if (!scene) {
  25076. return null;
  25077. }
  25078. var engine = scene.getEngine();
  25079. if (this._texture.isCube) {
  25080. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25081. }
  25082. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25083. };
  25084. BaseTexture.prototype.releaseInternalTexture = function () {
  25085. if (this._texture) {
  25086. this._texture.dispose();
  25087. this._texture = null;
  25088. }
  25089. };
  25090. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25091. get: function () {
  25092. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25093. return null;
  25094. }
  25095. if (!this._texture._sphericalPolynomial) {
  25096. this._texture._sphericalPolynomial =
  25097. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25098. }
  25099. return this._texture._sphericalPolynomial;
  25100. },
  25101. set: function (value) {
  25102. if (this._texture) {
  25103. this._texture._sphericalPolynomial = value;
  25104. }
  25105. },
  25106. enumerable: true,
  25107. configurable: true
  25108. });
  25109. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25110. get: function () {
  25111. if (this._texture) {
  25112. return this._texture._lodTextureHigh;
  25113. }
  25114. return null;
  25115. },
  25116. enumerable: true,
  25117. configurable: true
  25118. });
  25119. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25120. get: function () {
  25121. if (this._texture) {
  25122. return this._texture._lodTextureMid;
  25123. }
  25124. return null;
  25125. },
  25126. enumerable: true,
  25127. configurable: true
  25128. });
  25129. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25130. get: function () {
  25131. if (this._texture) {
  25132. return this._texture._lodTextureLow;
  25133. }
  25134. return null;
  25135. },
  25136. enumerable: true,
  25137. configurable: true
  25138. });
  25139. BaseTexture.prototype.dispose = function () {
  25140. if (!this._scene) {
  25141. return;
  25142. }
  25143. // Animations
  25144. this._scene.stopAnimation(this);
  25145. // Remove from scene
  25146. this._scene._removePendingData(this);
  25147. var index = this._scene.textures.indexOf(this);
  25148. if (index >= 0) {
  25149. this._scene.textures.splice(index, 1);
  25150. }
  25151. if (this._texture === undefined) {
  25152. return;
  25153. }
  25154. // Release
  25155. this.releaseInternalTexture();
  25156. // Callback
  25157. this.onDisposeObservable.notifyObservers(this);
  25158. this.onDisposeObservable.clear();
  25159. };
  25160. BaseTexture.prototype.serialize = function () {
  25161. if (!this.name) {
  25162. return null;
  25163. }
  25164. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25165. // Animations
  25166. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25167. return serializationObject;
  25168. };
  25169. BaseTexture.WhenAllReady = function (textures, callback) {
  25170. var numRemaining = textures.length;
  25171. if (numRemaining === 0) {
  25172. callback();
  25173. return;
  25174. }
  25175. var _loop_1 = function () {
  25176. texture = textures[i];
  25177. if (texture.isReady()) {
  25178. if (--numRemaining === 0) {
  25179. callback();
  25180. }
  25181. }
  25182. else {
  25183. onLoadObservable = texture.onLoadObservable;
  25184. var onLoadCallback_1 = function () {
  25185. onLoadObservable.removeCallback(onLoadCallback_1);
  25186. if (--numRemaining === 0) {
  25187. callback();
  25188. }
  25189. };
  25190. onLoadObservable.add(onLoadCallback_1);
  25191. }
  25192. };
  25193. var texture, onLoadObservable;
  25194. for (var i = 0; i < textures.length; i++) {
  25195. _loop_1();
  25196. }
  25197. };
  25198. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25199. __decorate([
  25200. BABYLON.serialize()
  25201. ], BaseTexture.prototype, "name", void 0);
  25202. __decorate([
  25203. BABYLON.serialize("hasAlpha")
  25204. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25205. __decorate([
  25206. BABYLON.serialize()
  25207. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25208. __decorate([
  25209. BABYLON.serialize()
  25210. ], BaseTexture.prototype, "level", void 0);
  25211. __decorate([
  25212. BABYLON.serialize()
  25213. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25214. __decorate([
  25215. BABYLON.serialize("coordinatesMode")
  25216. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25217. __decorate([
  25218. BABYLON.serialize()
  25219. ], BaseTexture.prototype, "wrapU", void 0);
  25220. __decorate([
  25221. BABYLON.serialize()
  25222. ], BaseTexture.prototype, "wrapV", void 0);
  25223. __decorate([
  25224. BABYLON.serialize()
  25225. ], BaseTexture.prototype, "wrapR", void 0);
  25226. __decorate([
  25227. BABYLON.serialize()
  25228. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25229. __decorate([
  25230. BABYLON.serialize()
  25231. ], BaseTexture.prototype, "isCube", void 0);
  25232. __decorate([
  25233. BABYLON.serialize()
  25234. ], BaseTexture.prototype, "is3D", void 0);
  25235. __decorate([
  25236. BABYLON.serialize()
  25237. ], BaseTexture.prototype, "gammaSpace", void 0);
  25238. __decorate([
  25239. BABYLON.serialize()
  25240. ], BaseTexture.prototype, "invertZ", void 0);
  25241. __decorate([
  25242. BABYLON.serialize()
  25243. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25244. __decorate([
  25245. BABYLON.serialize()
  25246. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25247. __decorate([
  25248. BABYLON.serialize()
  25249. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25250. __decorate([
  25251. BABYLON.serialize()
  25252. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25253. return BaseTexture;
  25254. }());
  25255. BABYLON.BaseTexture = BaseTexture;
  25256. })(BABYLON || (BABYLON = {}));
  25257. //# sourceMappingURL=babylon.baseTexture.js.map
  25258. var BABYLON;
  25259. (function (BABYLON) {
  25260. var Texture = /** @class */ (function (_super) {
  25261. __extends(Texture, _super);
  25262. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25263. if (noMipmap === void 0) { noMipmap = false; }
  25264. if (invertY === void 0) { invertY = true; }
  25265. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25266. if (onLoad === void 0) { onLoad = null; }
  25267. if (onError === void 0) { onError = null; }
  25268. if (buffer === void 0) { buffer = null; }
  25269. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25270. var _this = _super.call(this, scene) || this;
  25271. _this.uOffset = 0;
  25272. _this.vOffset = 0;
  25273. _this.uScale = 1.0;
  25274. _this.vScale = 1.0;
  25275. _this.uAng = 0;
  25276. _this.vAng = 0;
  25277. _this.wAng = 0;
  25278. _this._isBlocking = true;
  25279. _this.name = url || "";
  25280. _this.url = url;
  25281. _this._noMipmap = noMipmap;
  25282. _this._invertY = invertY;
  25283. _this._samplingMode = samplingMode;
  25284. _this._buffer = buffer;
  25285. _this._deleteBuffer = deleteBuffer;
  25286. if (format) {
  25287. _this._format = format;
  25288. }
  25289. scene = _this.getScene();
  25290. if (!scene) {
  25291. return _this;
  25292. }
  25293. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25294. var load = function () {
  25295. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25296. _this.onLoadObservable.notifyObservers(_this);
  25297. }
  25298. if (onLoad) {
  25299. onLoad();
  25300. }
  25301. if (!_this.isBlocking && scene) {
  25302. scene.resetCachedMaterial();
  25303. }
  25304. };
  25305. if (!_this.url) {
  25306. _this._delayedOnLoad = load;
  25307. _this._delayedOnError = onError;
  25308. return _this;
  25309. }
  25310. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  25311. if (!_this._texture) {
  25312. if (!scene.useDelayedTextureLoading) {
  25313. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  25314. if (deleteBuffer) {
  25315. delete _this._buffer;
  25316. }
  25317. }
  25318. else {
  25319. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25320. _this._delayedOnLoad = load;
  25321. _this._delayedOnError = onError;
  25322. }
  25323. }
  25324. else {
  25325. if (_this._texture.isReady) {
  25326. BABYLON.Tools.SetImmediate(function () { return load(); });
  25327. }
  25328. else {
  25329. _this._texture.onLoadedObservable.add(load);
  25330. }
  25331. }
  25332. return _this;
  25333. }
  25334. Object.defineProperty(Texture.prototype, "noMipmap", {
  25335. get: function () {
  25336. return this._noMipmap;
  25337. },
  25338. enumerable: true,
  25339. configurable: true
  25340. });
  25341. Object.defineProperty(Texture.prototype, "isBlocking", {
  25342. get: function () {
  25343. return this._isBlocking;
  25344. },
  25345. set: function (value) {
  25346. this._isBlocking = value;
  25347. },
  25348. enumerable: true,
  25349. configurable: true
  25350. });
  25351. Object.defineProperty(Texture.prototype, "samplingMode", {
  25352. get: function () {
  25353. return this._samplingMode;
  25354. },
  25355. enumerable: true,
  25356. configurable: true
  25357. });
  25358. Texture.prototype.updateURL = function (url) {
  25359. this.url = url;
  25360. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25361. this.delayLoad();
  25362. };
  25363. Texture.prototype.delayLoad = function () {
  25364. var _this = this;
  25365. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25366. return;
  25367. }
  25368. var scene = this.getScene();
  25369. if (!scene) {
  25370. return;
  25371. }
  25372. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25373. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  25374. if (!this._texture) {
  25375. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  25376. if (this._deleteBuffer) {
  25377. delete this._buffer;
  25378. }
  25379. }
  25380. else {
  25381. if (this._texture.isReady) {
  25382. BABYLON.Tools.SetImmediate(function () {
  25383. if (!_this._delayedOnLoad) {
  25384. return;
  25385. }
  25386. _this._delayedOnLoad();
  25387. });
  25388. }
  25389. else {
  25390. if (this._delayedOnLoad) {
  25391. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25392. }
  25393. }
  25394. }
  25395. };
  25396. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25397. if (!this._texture) {
  25398. return;
  25399. }
  25400. var scene = this.getScene();
  25401. if (!scene) {
  25402. return;
  25403. }
  25404. this._samplingMode = samplingMode;
  25405. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25406. };
  25407. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25408. x *= this.uScale;
  25409. y *= this.vScale;
  25410. x -= 0.5 * this.uScale;
  25411. y -= 0.5 * this.vScale;
  25412. z -= 0.5;
  25413. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25414. t.x += 0.5 * this.uScale + this.uOffset;
  25415. t.y += 0.5 * this.vScale + this.vOffset;
  25416. t.z += 0.5;
  25417. };
  25418. Texture.prototype.getTextureMatrix = function () {
  25419. var _this = this;
  25420. if (this.uOffset === this._cachedUOffset &&
  25421. this.vOffset === this._cachedVOffset &&
  25422. this.uScale === this._cachedUScale &&
  25423. this.vScale === this._cachedVScale &&
  25424. this.uAng === this._cachedUAng &&
  25425. this.vAng === this._cachedVAng &&
  25426. this.wAng === this._cachedWAng) {
  25427. return this._cachedTextureMatrix;
  25428. }
  25429. this._cachedUOffset = this.uOffset;
  25430. this._cachedVOffset = this.vOffset;
  25431. this._cachedUScale = this.uScale;
  25432. this._cachedVScale = this.vScale;
  25433. this._cachedUAng = this.uAng;
  25434. this._cachedVAng = this.vAng;
  25435. this._cachedWAng = this.wAng;
  25436. if (!this._cachedTextureMatrix) {
  25437. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25438. this._rowGenerationMatrix = new BABYLON.Matrix();
  25439. this._t0 = BABYLON.Vector3.Zero();
  25440. this._t1 = BABYLON.Vector3.Zero();
  25441. this._t2 = BABYLON.Vector3.Zero();
  25442. }
  25443. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25444. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25445. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25446. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25447. this._t1.subtractInPlace(this._t0);
  25448. this._t2.subtractInPlace(this._t0);
  25449. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25450. this._cachedTextureMatrix.m[0] = this._t1.x;
  25451. this._cachedTextureMatrix.m[1] = this._t1.y;
  25452. this._cachedTextureMatrix.m[2] = this._t1.z;
  25453. this._cachedTextureMatrix.m[4] = this._t2.x;
  25454. this._cachedTextureMatrix.m[5] = this._t2.y;
  25455. this._cachedTextureMatrix.m[6] = this._t2.z;
  25456. this._cachedTextureMatrix.m[8] = this._t0.x;
  25457. this._cachedTextureMatrix.m[9] = this._t0.y;
  25458. this._cachedTextureMatrix.m[10] = this._t0.z;
  25459. var scene = this.getScene();
  25460. if (!scene) {
  25461. return this._cachedTextureMatrix;
  25462. }
  25463. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25464. return mat.hasTexture(_this);
  25465. });
  25466. return this._cachedTextureMatrix;
  25467. };
  25468. Texture.prototype.getReflectionTextureMatrix = function () {
  25469. var _this = this;
  25470. var scene = this.getScene();
  25471. if (!scene) {
  25472. return this._cachedTextureMatrix;
  25473. }
  25474. if (this.uOffset === this._cachedUOffset &&
  25475. this.vOffset === this._cachedVOffset &&
  25476. this.uScale === this._cachedUScale &&
  25477. this.vScale === this._cachedVScale &&
  25478. this.coordinatesMode === this._cachedCoordinatesMode) {
  25479. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25480. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25481. return this._cachedTextureMatrix;
  25482. }
  25483. }
  25484. else {
  25485. return this._cachedTextureMatrix;
  25486. }
  25487. }
  25488. if (!this._cachedTextureMatrix) {
  25489. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25490. }
  25491. if (!this._projectionModeMatrix) {
  25492. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25493. }
  25494. this._cachedUOffset = this.uOffset;
  25495. this._cachedVOffset = this.vOffset;
  25496. this._cachedUScale = this.uScale;
  25497. this._cachedVScale = this.vScale;
  25498. this._cachedCoordinatesMode = this.coordinatesMode;
  25499. switch (this.coordinatesMode) {
  25500. case Texture.PLANAR_MODE:
  25501. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25502. this._cachedTextureMatrix[0] = this.uScale;
  25503. this._cachedTextureMatrix[5] = this.vScale;
  25504. this._cachedTextureMatrix[12] = this.uOffset;
  25505. this._cachedTextureMatrix[13] = this.vOffset;
  25506. break;
  25507. case Texture.PROJECTION_MODE:
  25508. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25509. this._projectionModeMatrix.m[0] = 0.5;
  25510. this._projectionModeMatrix.m[5] = -0.5;
  25511. this._projectionModeMatrix.m[10] = 0.0;
  25512. this._projectionModeMatrix.m[12] = 0.5;
  25513. this._projectionModeMatrix.m[13] = 0.5;
  25514. this._projectionModeMatrix.m[14] = 1.0;
  25515. this._projectionModeMatrix.m[15] = 1.0;
  25516. var projectionMatrix = scene.getProjectionMatrix();
  25517. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25518. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25519. break;
  25520. default:
  25521. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25522. break;
  25523. }
  25524. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25525. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25526. });
  25527. return this._cachedTextureMatrix;
  25528. };
  25529. Texture.prototype.clone = function () {
  25530. var _this = this;
  25531. return BABYLON.SerializationHelper.Clone(function () {
  25532. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25533. }, this);
  25534. };
  25535. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25536. get: function () {
  25537. if (!this._onLoadObservable) {
  25538. this._onLoadObservable = new BABYLON.Observable();
  25539. }
  25540. return this._onLoadObservable;
  25541. },
  25542. enumerable: true,
  25543. configurable: true
  25544. });
  25545. Texture.prototype.serialize = function () {
  25546. var serializationObject = _super.prototype.serialize.call(this);
  25547. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25548. serializationObject.base64String = this._buffer;
  25549. serializationObject.name = serializationObject.name.replace("data:", "");
  25550. }
  25551. return serializationObject;
  25552. };
  25553. Texture.prototype.getClassName = function () {
  25554. return "Texture";
  25555. };
  25556. Texture.prototype.dispose = function () {
  25557. _super.prototype.dispose.call(this);
  25558. if (this.onLoadObservable) {
  25559. this.onLoadObservable.clear();
  25560. this._onLoadObservable = null;
  25561. }
  25562. this._delayedOnLoad = null;
  25563. this._delayedOnError = null;
  25564. };
  25565. // Statics
  25566. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25567. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25568. if (onLoad === void 0) { onLoad = null; }
  25569. if (onError === void 0) { onError = null; }
  25570. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25571. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25572. };
  25573. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25574. if (parsedTexture.customType) {
  25575. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25576. // Update Sampling Mode
  25577. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25578. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25579. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25580. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25581. }
  25582. }
  25583. return parsedCustomTexture;
  25584. }
  25585. if (parsedTexture.isCube) {
  25586. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25587. }
  25588. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25589. return null;
  25590. }
  25591. var texture = BABYLON.SerializationHelper.Parse(function () {
  25592. var generateMipMaps = true;
  25593. if (parsedTexture.noMipmap) {
  25594. generateMipMaps = false;
  25595. }
  25596. if (parsedTexture.mirrorPlane) {
  25597. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25598. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25599. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25600. return mirrorTexture;
  25601. }
  25602. else if (parsedTexture.isRenderTarget) {
  25603. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25604. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25605. return renderTargetTexture;
  25606. }
  25607. else {
  25608. var texture;
  25609. if (parsedTexture.base64String) {
  25610. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25611. }
  25612. else {
  25613. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25614. }
  25615. return texture;
  25616. }
  25617. }, parsedTexture, scene);
  25618. // Update Sampling Mode
  25619. if (parsedTexture.samplingMode) {
  25620. var sampling = parsedTexture.samplingMode;
  25621. if (texture._samplingMode !== sampling) {
  25622. texture.updateSamplingMode(sampling);
  25623. }
  25624. }
  25625. // Animations
  25626. if (parsedTexture.animations) {
  25627. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25628. var parsedAnimation = parsedTexture.animations[animationIndex];
  25629. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25630. }
  25631. }
  25632. return texture;
  25633. };
  25634. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25635. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25636. if (noMipmap === void 0) { noMipmap = false; }
  25637. if (invertY === void 0) { invertY = true; }
  25638. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25639. if (onLoad === void 0) { onLoad = null; }
  25640. if (onError === void 0) { onError = null; }
  25641. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25642. if (name.substr(0, 5) !== "data:") {
  25643. name = "data:" + name;
  25644. }
  25645. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25646. };
  25647. // Constants
  25648. Texture.NEAREST_SAMPLINGMODE = 1;
  25649. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25650. Texture.BILINEAR_SAMPLINGMODE = 2;
  25651. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25652. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25653. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25654. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25655. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25656. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25657. Texture.NEAREST_LINEAR = 7;
  25658. Texture.NEAREST_NEAREST = 8;
  25659. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25660. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25661. Texture.LINEAR_LINEAR = 11;
  25662. Texture.LINEAR_NEAREST = 12;
  25663. Texture.EXPLICIT_MODE = 0;
  25664. Texture.SPHERICAL_MODE = 1;
  25665. Texture.PLANAR_MODE = 2;
  25666. Texture.CUBIC_MODE = 3;
  25667. Texture.PROJECTION_MODE = 4;
  25668. Texture.SKYBOX_MODE = 5;
  25669. Texture.INVCUBIC_MODE = 6;
  25670. Texture.EQUIRECTANGULAR_MODE = 7;
  25671. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25672. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25673. Texture.CLAMP_ADDRESSMODE = 0;
  25674. Texture.WRAP_ADDRESSMODE = 1;
  25675. Texture.MIRROR_ADDRESSMODE = 2;
  25676. __decorate([
  25677. BABYLON.serialize()
  25678. ], Texture.prototype, "url", void 0);
  25679. __decorate([
  25680. BABYLON.serialize()
  25681. ], Texture.prototype, "uOffset", void 0);
  25682. __decorate([
  25683. BABYLON.serialize()
  25684. ], Texture.prototype, "vOffset", void 0);
  25685. __decorate([
  25686. BABYLON.serialize()
  25687. ], Texture.prototype, "uScale", void 0);
  25688. __decorate([
  25689. BABYLON.serialize()
  25690. ], Texture.prototype, "vScale", void 0);
  25691. __decorate([
  25692. BABYLON.serialize()
  25693. ], Texture.prototype, "uAng", void 0);
  25694. __decorate([
  25695. BABYLON.serialize()
  25696. ], Texture.prototype, "vAng", void 0);
  25697. __decorate([
  25698. BABYLON.serialize()
  25699. ], Texture.prototype, "wAng", void 0);
  25700. __decorate([
  25701. BABYLON.serialize()
  25702. ], Texture.prototype, "isBlocking", null);
  25703. return Texture;
  25704. }(BABYLON.BaseTexture));
  25705. BABYLON.Texture = Texture;
  25706. })(BABYLON || (BABYLON = {}));
  25707. //# sourceMappingURL=babylon.texture.js.map
  25708. var BABYLON;
  25709. (function (BABYLON) {
  25710. var _InstancesBatch = /** @class */ (function () {
  25711. function _InstancesBatch() {
  25712. this.mustReturn = false;
  25713. this.visibleInstances = new Array();
  25714. this.renderSelf = new Array();
  25715. }
  25716. return _InstancesBatch;
  25717. }());
  25718. BABYLON._InstancesBatch = _InstancesBatch;
  25719. var Mesh = /** @class */ (function (_super) {
  25720. __extends(Mesh, _super);
  25721. /**
  25722. * @constructor
  25723. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25724. * @param {Scene} scene The scene to add this mesh to.
  25725. * @param {Node} parent The parent of this mesh, if it has one
  25726. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25727. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25728. * When false, achieved by calling a clone(), also passing False.
  25729. * This will make creation of children, recursive.
  25730. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25731. */
  25732. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25733. if (scene === void 0) { scene = null; }
  25734. if (parent === void 0) { parent = null; }
  25735. if (source === void 0) { source = null; }
  25736. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25737. var _this = _super.call(this, name, scene) || this;
  25738. // Events
  25739. /**
  25740. * An event triggered before rendering the mesh
  25741. * @type {BABYLON.Observable}
  25742. */
  25743. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25744. /**
  25745. * An event triggered after rendering the mesh
  25746. * @type {BABYLON.Observable}
  25747. */
  25748. _this.onAfterRenderObservable = new BABYLON.Observable();
  25749. /**
  25750. * An event triggered before drawing the mesh
  25751. * @type {BABYLON.Observable}
  25752. */
  25753. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25754. // Members
  25755. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25756. _this.instances = new Array();
  25757. _this._LODLevels = new Array();
  25758. _this._visibleInstances = {};
  25759. _this._renderIdForInstances = new Array();
  25760. _this._batchCache = new _InstancesBatch();
  25761. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25762. // Use by builder only to know what orientation were the mesh build in.
  25763. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25764. _this.overrideMaterialSideOrientation = null;
  25765. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25766. // Will be used to save a source mesh reference, If any
  25767. _this._source = null;
  25768. scene = _this.getScene();
  25769. if (source) {
  25770. // Source mesh
  25771. _this._source = source;
  25772. // Geometry
  25773. if (source._geometry) {
  25774. source._geometry.applyToMesh(_this);
  25775. }
  25776. // Deep copy
  25777. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25778. // Metadata
  25779. if (source.metadata && source.metadata.clone) {
  25780. _this.metadata = source.metadata.clone();
  25781. }
  25782. else {
  25783. _this.metadata = source.metadata;
  25784. }
  25785. // Tags
  25786. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25787. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25788. }
  25789. // Parent
  25790. _this.parent = source.parent;
  25791. // Pivot
  25792. _this.setPivotMatrix(source.getPivotMatrix());
  25793. _this.id = name + "." + source.id;
  25794. // Material
  25795. _this.material = source.material;
  25796. var index;
  25797. if (!doNotCloneChildren) {
  25798. // Children
  25799. var directDescendants = source.getDescendants(true);
  25800. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25801. var child = directDescendants[index_1];
  25802. if (child.clone) {
  25803. child.clone(name + "." + child.name, _this);
  25804. }
  25805. }
  25806. }
  25807. // Physics clone
  25808. var physicsEngine = _this.getScene().getPhysicsEngine();
  25809. if (clonePhysicsImpostor && physicsEngine) {
  25810. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25811. if (impostor) {
  25812. _this.physicsImpostor = impostor.clone(_this);
  25813. }
  25814. }
  25815. // Particles
  25816. for (index = 0; index < scene.particleSystems.length; index++) {
  25817. var system = scene.particleSystems[index];
  25818. if (system.emitter === source) {
  25819. system.clone(system.name, _this);
  25820. }
  25821. }
  25822. _this.computeWorldMatrix(true);
  25823. }
  25824. // Parent
  25825. if (parent !== null) {
  25826. _this.parent = parent;
  25827. }
  25828. return _this;
  25829. }
  25830. Object.defineProperty(Mesh, "FRONTSIDE", {
  25831. /**
  25832. * Mesh side orientation : usually the external or front surface
  25833. */
  25834. get: function () {
  25835. return Mesh._FRONTSIDE;
  25836. },
  25837. enumerable: true,
  25838. configurable: true
  25839. });
  25840. Object.defineProperty(Mesh, "BACKSIDE", {
  25841. /**
  25842. * Mesh side orientation : usually the internal or back surface
  25843. */
  25844. get: function () {
  25845. return Mesh._BACKSIDE;
  25846. },
  25847. enumerable: true,
  25848. configurable: true
  25849. });
  25850. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25851. /**
  25852. * Mesh side orientation : both internal and external or front and back surfaces
  25853. */
  25854. get: function () {
  25855. return Mesh._DOUBLESIDE;
  25856. },
  25857. enumerable: true,
  25858. configurable: true
  25859. });
  25860. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25861. /**
  25862. * Mesh side orientation : by default, `FRONTSIDE`
  25863. */
  25864. get: function () {
  25865. return Mesh._DEFAULTSIDE;
  25866. },
  25867. enumerable: true,
  25868. configurable: true
  25869. });
  25870. Object.defineProperty(Mesh, "NO_CAP", {
  25871. /**
  25872. * Mesh cap setting : no cap
  25873. */
  25874. get: function () {
  25875. return Mesh._NO_CAP;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(Mesh, "CAP_START", {
  25881. /**
  25882. * Mesh cap setting : one cap at the beginning of the mesh
  25883. */
  25884. get: function () {
  25885. return Mesh._CAP_START;
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. Object.defineProperty(Mesh, "CAP_END", {
  25891. /**
  25892. * Mesh cap setting : one cap at the end of the mesh
  25893. */
  25894. get: function () {
  25895. return Mesh._CAP_END;
  25896. },
  25897. enumerable: true,
  25898. configurable: true
  25899. });
  25900. Object.defineProperty(Mesh, "CAP_ALL", {
  25901. /**
  25902. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25903. */
  25904. get: function () {
  25905. return Mesh._CAP_ALL;
  25906. },
  25907. enumerable: true,
  25908. configurable: true
  25909. });
  25910. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25911. set: function (callback) {
  25912. if (this._onBeforeDrawObserver) {
  25913. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25914. }
  25915. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25916. },
  25917. enumerable: true,
  25918. configurable: true
  25919. });
  25920. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25921. get: function () {
  25922. return this._morphTargetManager;
  25923. },
  25924. set: function (value) {
  25925. if (this._morphTargetManager === value) {
  25926. return;
  25927. }
  25928. this._morphTargetManager = value;
  25929. this._syncGeometryWithMorphTargetManager();
  25930. },
  25931. enumerable: true,
  25932. configurable: true
  25933. });
  25934. Object.defineProperty(Mesh.prototype, "source", {
  25935. get: function () {
  25936. return this._source;
  25937. },
  25938. enumerable: true,
  25939. configurable: true
  25940. });
  25941. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25942. get: function () {
  25943. return this._unIndexed;
  25944. },
  25945. set: function (value) {
  25946. if (this._unIndexed !== value) {
  25947. this._unIndexed = value;
  25948. this._markSubMeshesAsAttributesDirty();
  25949. }
  25950. },
  25951. enumerable: true,
  25952. configurable: true
  25953. });
  25954. // Methods
  25955. /**
  25956. * Returns the string "Mesh".
  25957. */
  25958. Mesh.prototype.getClassName = function () {
  25959. return "Mesh";
  25960. };
  25961. /**
  25962. * Returns a string.
  25963. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25964. */
  25965. Mesh.prototype.toString = function (fullDetails) {
  25966. var ret = _super.prototype.toString.call(this, fullDetails);
  25967. ret += ", n vertices: " + this.getTotalVertices();
  25968. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25969. if (this.animations) {
  25970. for (var i = 0; i < this.animations.length; i++) {
  25971. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25972. }
  25973. }
  25974. if (fullDetails) {
  25975. if (this._geometry) {
  25976. var ib = this.getIndices();
  25977. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25978. if (vb && ib) {
  25979. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25980. }
  25981. }
  25982. else {
  25983. ret += ", flat shading: UNKNOWN";
  25984. }
  25985. }
  25986. return ret;
  25987. };
  25988. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25989. /**
  25990. * True if the mesh has some Levels Of Details (LOD).
  25991. * Returns a boolean.
  25992. */
  25993. get: function () {
  25994. return this._LODLevels.length > 0;
  25995. },
  25996. enumerable: true,
  25997. configurable: true
  25998. });
  25999. /**
  26000. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26001. * @returns an array of {BABYLON.MeshLODLevel}
  26002. */
  26003. Mesh.prototype.getLODLevels = function () {
  26004. return this._LODLevels;
  26005. };
  26006. Mesh.prototype._sortLODLevels = function () {
  26007. this._LODLevels.sort(function (a, b) {
  26008. if (a.distance < b.distance) {
  26009. return 1;
  26010. }
  26011. if (a.distance > b.distance) {
  26012. return -1;
  26013. }
  26014. return 0;
  26015. });
  26016. };
  26017. /**
  26018. * Add a mesh as LOD level triggered at the given distance.
  26019. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26020. * @param {number} distance The distance from the center of the object to show this level
  26021. * @param {Mesh} mesh The mesh to be added as LOD level
  26022. * @return {Mesh} This mesh (for chaining)
  26023. */
  26024. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26025. if (mesh && mesh._masterMesh) {
  26026. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26027. return this;
  26028. }
  26029. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26030. this._LODLevels.push(level);
  26031. if (mesh) {
  26032. mesh._masterMesh = this;
  26033. }
  26034. this._sortLODLevels();
  26035. return this;
  26036. };
  26037. /**
  26038. * Returns the LOD level mesh at the passed distance or null if not found.
  26039. * It is related to the method `addLODLevel(distance, mesh)`.
  26040. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26041. * Returns an object Mesh or `null`.
  26042. */
  26043. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26044. for (var index = 0; index < this._LODLevels.length; index++) {
  26045. var level = this._LODLevels[index];
  26046. if (level.distance === distance) {
  26047. return level.mesh;
  26048. }
  26049. }
  26050. return null;
  26051. };
  26052. /**
  26053. * Remove a mesh from the LOD array
  26054. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26055. * @param {Mesh} mesh The mesh to be removed.
  26056. * @return {Mesh} This mesh (for chaining)
  26057. */
  26058. Mesh.prototype.removeLODLevel = function (mesh) {
  26059. for (var index = 0; index < this._LODLevels.length; index++) {
  26060. if (this._LODLevels[index].mesh === mesh) {
  26061. this._LODLevels.splice(index, 1);
  26062. if (mesh) {
  26063. mesh._masterMesh = null;
  26064. }
  26065. }
  26066. }
  26067. this._sortLODLevels();
  26068. return this;
  26069. };
  26070. /**
  26071. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26072. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26073. */
  26074. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26075. if (!this._LODLevels || this._LODLevels.length === 0) {
  26076. return this;
  26077. }
  26078. var bSphere;
  26079. if (boundingSphere) {
  26080. bSphere = boundingSphere;
  26081. }
  26082. else {
  26083. var boundingInfo = this.getBoundingInfo();
  26084. bSphere = boundingInfo.boundingSphere;
  26085. }
  26086. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26087. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26088. if (this.onLODLevelSelection) {
  26089. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26090. }
  26091. return this;
  26092. }
  26093. for (var index = 0; index < this._LODLevels.length; index++) {
  26094. var level = this._LODLevels[index];
  26095. if (level.distance < distanceToCamera) {
  26096. if (level.mesh) {
  26097. level.mesh._preActivate();
  26098. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26099. }
  26100. if (this.onLODLevelSelection) {
  26101. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26102. }
  26103. return level.mesh;
  26104. }
  26105. }
  26106. if (this.onLODLevelSelection) {
  26107. this.onLODLevelSelection(distanceToCamera, this, this);
  26108. }
  26109. return this;
  26110. };
  26111. Object.defineProperty(Mesh.prototype, "geometry", {
  26112. /**
  26113. * Returns the mesh internal Geometry object.
  26114. */
  26115. get: function () {
  26116. return this._geometry;
  26117. },
  26118. enumerable: true,
  26119. configurable: true
  26120. });
  26121. /**
  26122. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26123. */
  26124. Mesh.prototype.getTotalVertices = function () {
  26125. if (this._geometry === null || this._geometry === undefined) {
  26126. return 0;
  26127. }
  26128. return this._geometry.getTotalVertices();
  26129. };
  26130. /**
  26131. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26132. * 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.
  26133. * You can force the copy with forceCopy === true
  26134. * Returns null if the mesh has no geometry or no vertex buffer.
  26135. * Possible `kind` values :
  26136. * - BABYLON.VertexBuffer.PositionKind
  26137. * - BABYLON.VertexBuffer.UVKind
  26138. * - BABYLON.VertexBuffer.UV2Kind
  26139. * - BABYLON.VertexBuffer.UV3Kind
  26140. * - BABYLON.VertexBuffer.UV4Kind
  26141. * - BABYLON.VertexBuffer.UV5Kind
  26142. * - BABYLON.VertexBuffer.UV6Kind
  26143. * - BABYLON.VertexBuffer.ColorKind
  26144. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26145. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26146. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26147. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26148. */
  26149. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26150. if (!this._geometry) {
  26151. return null;
  26152. }
  26153. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26154. };
  26155. /**
  26156. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26157. * Returns `null` if the mesh has no geometry.
  26158. * Possible `kind` values :
  26159. * - BABYLON.VertexBuffer.PositionKind
  26160. * - BABYLON.VertexBuffer.UVKind
  26161. * - BABYLON.VertexBuffer.UV2Kind
  26162. * - BABYLON.VertexBuffer.UV3Kind
  26163. * - BABYLON.VertexBuffer.UV4Kind
  26164. * - BABYLON.VertexBuffer.UV5Kind
  26165. * - BABYLON.VertexBuffer.UV6Kind
  26166. * - BABYLON.VertexBuffer.ColorKind
  26167. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26168. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26169. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26170. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26171. */
  26172. Mesh.prototype.getVertexBuffer = function (kind) {
  26173. if (!this._geometry) {
  26174. return null;
  26175. }
  26176. return this._geometry.getVertexBuffer(kind);
  26177. };
  26178. /**
  26179. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26180. * Possible `kind` values :
  26181. * - BABYLON.VertexBuffer.PositionKind
  26182. * - BABYLON.VertexBuffer.UVKind
  26183. * - BABYLON.VertexBuffer.UV2Kind
  26184. * - BABYLON.VertexBuffer.UV3Kind
  26185. * - BABYLON.VertexBuffer.UV4Kind
  26186. * - BABYLON.VertexBuffer.UV5Kind
  26187. * - BABYLON.VertexBuffer.UV6Kind
  26188. * - BABYLON.VertexBuffer.ColorKind
  26189. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26190. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26191. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26192. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26193. */
  26194. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26195. if (!this._geometry) {
  26196. if (this._delayInfo) {
  26197. return this._delayInfo.indexOf(kind) !== -1;
  26198. }
  26199. return false;
  26200. }
  26201. return this._geometry.isVerticesDataPresent(kind);
  26202. };
  26203. /**
  26204. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26205. * Possible `kind` values :
  26206. * - BABYLON.VertexBuffer.PositionKind
  26207. * - BABYLON.VertexBuffer.UVKind
  26208. * - BABYLON.VertexBuffer.UV2Kind
  26209. * - BABYLON.VertexBuffer.UV3Kind
  26210. * - BABYLON.VertexBuffer.UV4Kind
  26211. * - BABYLON.VertexBuffer.UV5Kind
  26212. * - BABYLON.VertexBuffer.UV6Kind
  26213. * - BABYLON.VertexBuffer.ColorKind
  26214. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26215. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26216. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26217. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26218. */
  26219. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26220. if (!this._geometry) {
  26221. if (this._delayInfo) {
  26222. return this._delayInfo.indexOf(kind) !== -1;
  26223. }
  26224. return false;
  26225. }
  26226. return this._geometry.isVertexBufferUpdatable(kind);
  26227. };
  26228. /**
  26229. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26230. * Possible `kind` values :
  26231. * - BABYLON.VertexBuffer.PositionKind
  26232. * - BABYLON.VertexBuffer.UVKind
  26233. * - BABYLON.VertexBuffer.UV2Kind
  26234. * - BABYLON.VertexBuffer.UV3Kind
  26235. * - BABYLON.VertexBuffer.UV4Kind
  26236. * - BABYLON.VertexBuffer.UV5Kind
  26237. * - BABYLON.VertexBuffer.UV6Kind
  26238. * - BABYLON.VertexBuffer.ColorKind
  26239. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26240. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26241. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26242. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26243. */
  26244. Mesh.prototype.getVerticesDataKinds = function () {
  26245. if (!this._geometry) {
  26246. var result = new Array();
  26247. if (this._delayInfo) {
  26248. this._delayInfo.forEach(function (kind, index, array) {
  26249. result.push(kind);
  26250. });
  26251. }
  26252. return result;
  26253. }
  26254. return this._geometry.getVerticesDataKinds();
  26255. };
  26256. /**
  26257. * Returns a positive integer : the total number of indices in this mesh geometry.
  26258. * Returns zero if the mesh has no geometry.
  26259. */
  26260. Mesh.prototype.getTotalIndices = function () {
  26261. if (!this._geometry) {
  26262. return 0;
  26263. }
  26264. return this._geometry.getTotalIndices();
  26265. };
  26266. /**
  26267. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26268. * 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.
  26269. * Returns an empty array if the mesh has no geometry.
  26270. */
  26271. Mesh.prototype.getIndices = function (copyWhenShared) {
  26272. if (!this._geometry) {
  26273. return [];
  26274. }
  26275. return this._geometry.getIndices(copyWhenShared);
  26276. };
  26277. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26278. get: function () {
  26279. return this._masterMesh !== null && this._masterMesh !== undefined;
  26280. },
  26281. enumerable: true,
  26282. configurable: true
  26283. });
  26284. /**
  26285. * Determine if the current mesh is ready to be rendered
  26286. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26287. * @returns true if all associated assets are ready (material, textures, shaders)
  26288. */
  26289. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26290. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26291. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26292. return false;
  26293. }
  26294. if (!_super.prototype.isReady.call(this)) {
  26295. return false;
  26296. }
  26297. if (!this.subMeshes || this.subMeshes.length === 0) {
  26298. return true;
  26299. }
  26300. var engine = this.getEngine();
  26301. var scene = this.getScene();
  26302. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  26303. this.computeWorldMatrix();
  26304. var mat = this.material || scene.defaultMaterial;
  26305. if (mat) {
  26306. if (mat.storeEffectOnSubMeshes) {
  26307. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26308. var subMesh = _a[_i];
  26309. var effectiveMaterial = subMesh.getMaterial();
  26310. if (effectiveMaterial) {
  26311. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26312. return false;
  26313. }
  26314. }
  26315. }
  26316. }
  26317. else {
  26318. if (!mat.isReady(this, hardwareInstancedRendering)) {
  26319. return false;
  26320. }
  26321. }
  26322. }
  26323. // Shadows
  26324. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  26325. var light = _c[_b];
  26326. var generator = light.getShadowGenerator();
  26327. if (generator) {
  26328. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  26329. var subMesh = _e[_d];
  26330. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  26331. return false;
  26332. }
  26333. }
  26334. }
  26335. }
  26336. // LOD
  26337. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  26338. var lod = _g[_f];
  26339. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  26340. return false;
  26341. }
  26342. }
  26343. return true;
  26344. };
  26345. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  26346. /**
  26347. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  26348. * This property is pertinent only for updatable parametric shapes.
  26349. */
  26350. get: function () {
  26351. return this._areNormalsFrozen;
  26352. },
  26353. enumerable: true,
  26354. configurable: true
  26355. });
  26356. /**
  26357. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26358. * It has no effect at all on other shapes.
  26359. * It prevents the mesh normals from being recomputed on next `positions` array update.
  26360. * Returns the Mesh.
  26361. */
  26362. Mesh.prototype.freezeNormals = function () {
  26363. this._areNormalsFrozen = true;
  26364. return this;
  26365. };
  26366. /**
  26367. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26368. * It has no effect at all on other shapes.
  26369. * It reactivates the mesh normals computation if it was previously frozen.
  26370. * Returns the Mesh.
  26371. */
  26372. Mesh.prototype.unfreezeNormals = function () {
  26373. this._areNormalsFrozen = false;
  26374. return this;
  26375. };
  26376. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  26377. /**
  26378. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  26379. */
  26380. set: function (count) {
  26381. this._overridenInstanceCount = count;
  26382. },
  26383. enumerable: true,
  26384. configurable: true
  26385. });
  26386. // Methods
  26387. Mesh.prototype._preActivate = function () {
  26388. var sceneRenderId = this.getScene().getRenderId();
  26389. if (this._preActivateId === sceneRenderId) {
  26390. return this;
  26391. }
  26392. this._preActivateId = sceneRenderId;
  26393. this._visibleInstances = null;
  26394. return this;
  26395. };
  26396. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26397. if (this._visibleInstances) {
  26398. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26399. }
  26400. return this;
  26401. };
  26402. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26403. if (!this._visibleInstances) {
  26404. this._visibleInstances = {};
  26405. this._visibleInstances.defaultRenderId = renderId;
  26406. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26407. }
  26408. if (!this._visibleInstances[renderId]) {
  26409. this._visibleInstances[renderId] = new Array();
  26410. }
  26411. this._visibleInstances[renderId].push(instance);
  26412. return this;
  26413. };
  26414. /**
  26415. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26416. * This means the mesh underlying bounding box and sphere are recomputed.
  26417. * Returns the Mesh.
  26418. */
  26419. Mesh.prototype.refreshBoundingInfo = function () {
  26420. return this._refreshBoundingInfo(false);
  26421. };
  26422. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26423. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26424. return this;
  26425. }
  26426. var data = this._getPositionData(applySkeleton);
  26427. if (data) {
  26428. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26429. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26430. }
  26431. if (this.subMeshes) {
  26432. for (var index = 0; index < this.subMeshes.length; index++) {
  26433. this.subMeshes[index].refreshBoundingInfo();
  26434. }
  26435. }
  26436. this._updateBoundingInfo();
  26437. return this;
  26438. };
  26439. Mesh.prototype._getPositionData = function (applySkeleton) {
  26440. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26441. if (data && applySkeleton && this.skeleton) {
  26442. data = BABYLON.Tools.Slice(data);
  26443. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26444. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26445. if (matricesWeightsData && matricesIndicesData) {
  26446. var needExtras = this.numBoneInfluencers > 4;
  26447. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26448. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26449. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26450. var tempVector = BABYLON.Tmp.Vector3[0];
  26451. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26452. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26453. var matWeightIdx = 0;
  26454. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26455. finalMatrix.reset();
  26456. var inf;
  26457. var weight;
  26458. for (inf = 0; inf < 4; inf++) {
  26459. weight = matricesWeightsData[matWeightIdx + inf];
  26460. if (weight <= 0)
  26461. break;
  26462. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26463. finalMatrix.addToSelf(tempMatrix);
  26464. }
  26465. if (needExtras) {
  26466. for (inf = 0; inf < 4; inf++) {
  26467. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26468. if (weight <= 0)
  26469. break;
  26470. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26471. finalMatrix.addToSelf(tempMatrix);
  26472. }
  26473. }
  26474. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26475. tempVector.toArray(data, index);
  26476. }
  26477. }
  26478. }
  26479. return data;
  26480. };
  26481. Mesh.prototype._createGlobalSubMesh = function (force) {
  26482. var totalVertices = this.getTotalVertices();
  26483. if (!totalVertices || !this.getIndices()) {
  26484. return null;
  26485. }
  26486. // Check if we need to recreate the submeshes
  26487. if (this.subMeshes && this.subMeshes.length > 0) {
  26488. var ib = this.getIndices();
  26489. if (!ib) {
  26490. return null;
  26491. }
  26492. var totalIndices = ib.length;
  26493. var needToRecreate = false;
  26494. if (force) {
  26495. needToRecreate = true;
  26496. }
  26497. else {
  26498. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26499. var submesh = _a[_i];
  26500. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26501. needToRecreate = true;
  26502. break;
  26503. }
  26504. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26505. needToRecreate = true;
  26506. break;
  26507. }
  26508. }
  26509. }
  26510. if (!needToRecreate) {
  26511. return this.subMeshes[0];
  26512. }
  26513. }
  26514. this.releaseSubMeshes();
  26515. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26516. };
  26517. Mesh.prototype.subdivide = function (count) {
  26518. if (count < 1) {
  26519. return;
  26520. }
  26521. var totalIndices = this.getTotalIndices();
  26522. var subdivisionSize = (totalIndices / count) | 0;
  26523. var offset = 0;
  26524. // Ensure that subdivisionSize is a multiple of 3
  26525. while (subdivisionSize % 3 !== 0) {
  26526. subdivisionSize++;
  26527. }
  26528. this.releaseSubMeshes();
  26529. for (var index = 0; index < count; index++) {
  26530. if (offset >= totalIndices) {
  26531. break;
  26532. }
  26533. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26534. offset += subdivisionSize;
  26535. }
  26536. this.synchronizeInstances();
  26537. };
  26538. /**
  26539. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26540. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26541. * The `data` are either a numeric array either a Float32Array.
  26542. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26543. * 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).
  26544. * Note that a new underlying VertexBuffer object is created each call.
  26545. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26546. *
  26547. * Possible `kind` values :
  26548. * - BABYLON.VertexBuffer.PositionKind
  26549. * - BABYLON.VertexBuffer.UVKind
  26550. * - BABYLON.VertexBuffer.UV2Kind
  26551. * - BABYLON.VertexBuffer.UV3Kind
  26552. * - BABYLON.VertexBuffer.UV4Kind
  26553. * - BABYLON.VertexBuffer.UV5Kind
  26554. * - BABYLON.VertexBuffer.UV6Kind
  26555. * - BABYLON.VertexBuffer.ColorKind
  26556. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26557. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26558. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26559. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26560. *
  26561. * Returns the Mesh.
  26562. */
  26563. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26564. if (updatable === void 0) { updatable = false; }
  26565. if (!this._geometry) {
  26566. var vertexData = new BABYLON.VertexData();
  26567. vertexData.set(data, kind);
  26568. var scene = this.getScene();
  26569. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26570. }
  26571. else {
  26572. this._geometry.setVerticesData(kind, data, updatable, stride);
  26573. }
  26574. return this;
  26575. };
  26576. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26577. if (updatable === void 0) { updatable = true; }
  26578. var vb = this.getVertexBuffer(kind);
  26579. if (!vb || vb.isUpdatable() === updatable) {
  26580. return;
  26581. }
  26582. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26583. };
  26584. /**
  26585. * Sets the mesh VertexBuffer.
  26586. * Returns the Mesh.
  26587. */
  26588. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26589. if (!this._geometry) {
  26590. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26591. }
  26592. this._geometry.setVerticesBuffer(buffer);
  26593. return this;
  26594. };
  26595. /**
  26596. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26597. * If the mesh has no geometry, it is simply returned as it is.
  26598. * The `data` are either a numeric array either a Float32Array.
  26599. * No new underlying VertexBuffer object is created.
  26600. * 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.
  26601. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26602. *
  26603. * Possible `kind` values :
  26604. * - BABYLON.VertexBuffer.PositionKind
  26605. * - BABYLON.VertexBuffer.UVKind
  26606. * - BABYLON.VertexBuffer.UV2Kind
  26607. * - BABYLON.VertexBuffer.UV3Kind
  26608. * - BABYLON.VertexBuffer.UV4Kind
  26609. * - BABYLON.VertexBuffer.UV5Kind
  26610. * - BABYLON.VertexBuffer.UV6Kind
  26611. * - BABYLON.VertexBuffer.ColorKind
  26612. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26613. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26614. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26615. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26616. *
  26617. * Returns the Mesh.
  26618. */
  26619. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26620. if (!this._geometry) {
  26621. return this;
  26622. }
  26623. if (!makeItUnique) {
  26624. this._geometry.updateVerticesData(kind, data, updateExtends);
  26625. }
  26626. else {
  26627. this.makeGeometryUnique();
  26628. this.updateVerticesData(kind, data, updateExtends, false);
  26629. }
  26630. return this;
  26631. };
  26632. /**
  26633. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26634. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26635. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26636. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26637. * Returns the Mesh.
  26638. */
  26639. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26640. if (computeNormals === void 0) { computeNormals = true; }
  26641. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26642. if (!positions) {
  26643. return this;
  26644. }
  26645. positionFunction(positions);
  26646. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26647. if (computeNormals) {
  26648. var indices = this.getIndices();
  26649. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26650. if (!normals) {
  26651. return this;
  26652. }
  26653. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26654. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26655. }
  26656. return this;
  26657. };
  26658. /**
  26659. * Creates a un-shared specific occurence of the geometry for the mesh.
  26660. * Returns the Mesh.
  26661. */
  26662. Mesh.prototype.makeGeometryUnique = function () {
  26663. if (!this._geometry) {
  26664. return this;
  26665. }
  26666. var oldGeometry = this._geometry;
  26667. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26668. oldGeometry.releaseForMesh(this, true);
  26669. geometry.applyToMesh(this);
  26670. return this;
  26671. };
  26672. /**
  26673. * Sets the mesh indices.
  26674. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26675. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26676. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26677. * This method creates a new index buffer each call.
  26678. * Returns the Mesh.
  26679. */
  26680. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26681. if (totalVertices === void 0) { totalVertices = null; }
  26682. if (updatable === void 0) { updatable = false; }
  26683. if (!this._geometry) {
  26684. var vertexData = new BABYLON.VertexData();
  26685. vertexData.indices = indices;
  26686. var scene = this.getScene();
  26687. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26688. }
  26689. else {
  26690. this._geometry.setIndices(indices, totalVertices, updatable);
  26691. }
  26692. return this;
  26693. };
  26694. /**
  26695. * Update the current index buffer
  26696. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26697. * Returns the Mesh.
  26698. */
  26699. Mesh.prototype.updateIndices = function (indices, offset) {
  26700. if (!this._geometry) {
  26701. return this;
  26702. }
  26703. this._geometry.updateIndices(indices, offset);
  26704. return this;
  26705. };
  26706. /**
  26707. * Invert the geometry to move from a right handed system to a left handed one.
  26708. * Returns the Mesh.
  26709. */
  26710. Mesh.prototype.toLeftHanded = function () {
  26711. if (!this._geometry) {
  26712. return this;
  26713. }
  26714. this._geometry.toLeftHanded();
  26715. return this;
  26716. };
  26717. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26718. if (!this._geometry) {
  26719. return this;
  26720. }
  26721. var engine = this.getScene().getEngine();
  26722. // Wireframe
  26723. var indexToBind;
  26724. if (this._unIndexed) {
  26725. indexToBind = null;
  26726. }
  26727. else {
  26728. switch (fillMode) {
  26729. case BABYLON.Material.PointFillMode:
  26730. indexToBind = null;
  26731. break;
  26732. case BABYLON.Material.WireFrameFillMode:
  26733. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26734. break;
  26735. default:
  26736. case BABYLON.Material.TriangleFillMode:
  26737. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26738. break;
  26739. }
  26740. }
  26741. // VBOs
  26742. this._geometry._bind(effect, indexToBind);
  26743. return this;
  26744. };
  26745. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26746. if (alternate === void 0) { alternate = false; }
  26747. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26748. return this;
  26749. }
  26750. this.onBeforeDrawObservable.notifyObservers(this);
  26751. var scene = this.getScene();
  26752. var engine = scene.getEngine();
  26753. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26754. // or triangles as points
  26755. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26756. }
  26757. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26758. // Triangles as wireframe
  26759. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26760. }
  26761. else {
  26762. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26763. }
  26764. if (scene._isAlternateRenderingEnabled && !alternate) {
  26765. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26766. if (!effect || !scene.activeCamera) {
  26767. return this;
  26768. }
  26769. scene._switchToAlternateCameraConfiguration(true);
  26770. this._effectiveMaterial.bindView(effect);
  26771. this._effectiveMaterial.bindViewProjection(effect);
  26772. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26773. this._draw(subMesh, fillMode, instancesCount, true);
  26774. engine.setViewport(scene.activeCamera.viewport);
  26775. scene._switchToAlternateCameraConfiguration(false);
  26776. this._effectiveMaterial.bindView(effect);
  26777. this._effectiveMaterial.bindViewProjection(effect);
  26778. }
  26779. return this;
  26780. };
  26781. /**
  26782. * Registers for this mesh a javascript function called just before the rendering process.
  26783. * This function is passed the current mesh.
  26784. * Return the Mesh.
  26785. */
  26786. Mesh.prototype.registerBeforeRender = function (func) {
  26787. this.onBeforeRenderObservable.add(func);
  26788. return this;
  26789. };
  26790. /**
  26791. * Disposes a previously registered javascript function called before the rendering.
  26792. * This function is passed the current mesh.
  26793. * Returns the Mesh.
  26794. */
  26795. Mesh.prototype.unregisterBeforeRender = function (func) {
  26796. this.onBeforeRenderObservable.removeCallback(func);
  26797. return this;
  26798. };
  26799. /**
  26800. * Registers for this mesh a javascript function called just after the rendering is complete.
  26801. * This function is passed the current mesh.
  26802. * Returns the Mesh.
  26803. */
  26804. Mesh.prototype.registerAfterRender = function (func) {
  26805. this.onAfterRenderObservable.add(func);
  26806. return this;
  26807. };
  26808. /**
  26809. * Disposes a previously registered javascript function called after the rendering.
  26810. * This function is passed the current mesh.
  26811. * Return the Mesh.
  26812. */
  26813. Mesh.prototype.unregisterAfterRender = function (func) {
  26814. this.onAfterRenderObservable.removeCallback(func);
  26815. return this;
  26816. };
  26817. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26818. var scene = this.getScene();
  26819. this._batchCache.mustReturn = false;
  26820. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26821. this._batchCache.visibleInstances[subMeshId] = null;
  26822. if (this._visibleInstances) {
  26823. var currentRenderId = scene.getRenderId();
  26824. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26825. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26826. var selfRenderId = this._renderId;
  26827. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26828. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26829. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26830. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26831. }
  26832. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26833. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26834. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26835. this._batchCache.mustReturn = true;
  26836. return this._batchCache;
  26837. }
  26838. if (currentRenderId !== selfRenderId) {
  26839. this._batchCache.renderSelf[subMeshId] = false;
  26840. }
  26841. }
  26842. this._renderIdForInstances[subMeshId] = currentRenderId;
  26843. }
  26844. return this._batchCache;
  26845. };
  26846. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26847. var visibleInstances = batch.visibleInstances[subMesh._id];
  26848. if (!visibleInstances) {
  26849. return this;
  26850. }
  26851. var matricesCount = visibleInstances.length + 1;
  26852. var bufferSize = matricesCount * 16 * 4;
  26853. var currentInstancesBufferSize = this._instancesBufferSize;
  26854. var instancesBuffer = this._instancesBuffer;
  26855. while (this._instancesBufferSize < bufferSize) {
  26856. this._instancesBufferSize *= 2;
  26857. }
  26858. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26859. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26860. }
  26861. var offset = 0;
  26862. var instancesCount = 0;
  26863. var world = this.getWorldMatrix();
  26864. if (batch.renderSelf[subMesh._id]) {
  26865. world.copyToArray(this._instancesData, offset);
  26866. offset += 16;
  26867. instancesCount++;
  26868. }
  26869. if (visibleInstances) {
  26870. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26871. var instance = visibleInstances[instanceIndex];
  26872. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26873. offset += 16;
  26874. instancesCount++;
  26875. }
  26876. }
  26877. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26878. if (instancesBuffer) {
  26879. instancesBuffer.dispose();
  26880. }
  26881. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26882. this._instancesBuffer = instancesBuffer;
  26883. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26884. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26885. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26886. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26887. }
  26888. else {
  26889. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26890. }
  26891. this._bind(subMesh, effect, fillMode);
  26892. this._draw(subMesh, fillMode, instancesCount);
  26893. engine.unbindInstanceAttributes();
  26894. return this;
  26895. };
  26896. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26897. var scene = this.getScene();
  26898. var engine = scene.getEngine();
  26899. if (hardwareInstancedRendering) {
  26900. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26901. }
  26902. else {
  26903. if (batch.renderSelf[subMesh._id]) {
  26904. // Draw
  26905. if (onBeforeDraw) {
  26906. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26907. }
  26908. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26909. }
  26910. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26911. if (visibleInstancesForSubMesh) {
  26912. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26913. var instance = visibleInstancesForSubMesh[instanceIndex];
  26914. // World
  26915. var world = instance.getWorldMatrix();
  26916. if (onBeforeDraw) {
  26917. onBeforeDraw(true, world, effectiveMaterial);
  26918. }
  26919. // Draw
  26920. this._draw(subMesh, fillMode);
  26921. }
  26922. }
  26923. }
  26924. return this;
  26925. };
  26926. /**
  26927. * Triggers the draw call for the mesh.
  26928. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26929. * Returns the Mesh.
  26930. */
  26931. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26932. this.checkOcclusionQuery();
  26933. if (this._isOccluded) {
  26934. return this;
  26935. }
  26936. var scene = this.getScene();
  26937. // Managing instances
  26938. var batch = this._getInstancesRenderList(subMesh._id);
  26939. if (batch.mustReturn) {
  26940. return this;
  26941. }
  26942. // Checking geometry state
  26943. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26944. return this;
  26945. }
  26946. this.onBeforeRenderObservable.notifyObservers(this);
  26947. var engine = scene.getEngine();
  26948. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26949. // Material
  26950. var material = subMesh.getMaterial();
  26951. if (!material) {
  26952. return this;
  26953. }
  26954. this._effectiveMaterial = material;
  26955. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26956. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26957. return this;
  26958. }
  26959. }
  26960. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26961. return this;
  26962. }
  26963. // Alpha mode
  26964. if (enableAlphaMode) {
  26965. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26966. }
  26967. // Outline - step 1
  26968. var savedDepthWrite = engine.getDepthWrite();
  26969. if (this.renderOutline) {
  26970. engine.setDepthWrite(false);
  26971. scene.getOutlineRenderer().render(subMesh, batch);
  26972. engine.setDepthWrite(savedDepthWrite);
  26973. }
  26974. var effect;
  26975. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26976. effect = subMesh.effect;
  26977. }
  26978. else {
  26979. effect = this._effectiveMaterial.getEffect();
  26980. }
  26981. if (!effect) {
  26982. return this;
  26983. }
  26984. var sideOrientation = this.overrideMaterialSideOrientation;
  26985. if (sideOrientation == null) {
  26986. sideOrientation = this._effectiveMaterial.sideOrientation;
  26987. if (this._getWorldMatrixDeterminant() < 0) {
  26988. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26989. }
  26990. }
  26991. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26992. if (this._effectiveMaterial.forceDepthWrite) {
  26993. engine.setDepthWrite(true);
  26994. }
  26995. // Bind
  26996. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26997. if (!hardwareInstancedRendering) {
  26998. this._bind(subMesh, effect, fillMode);
  26999. }
  27000. var world = this.getWorldMatrix();
  27001. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27002. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27003. }
  27004. else {
  27005. this._effectiveMaterial.bind(world, this);
  27006. }
  27007. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27008. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27009. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27010. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27011. }
  27012. // Draw
  27013. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27014. // Unbind
  27015. this._effectiveMaterial.unbind();
  27016. // Outline - step 2
  27017. if (this.renderOutline && savedDepthWrite) {
  27018. engine.setDepthWrite(true);
  27019. engine.setColorWrite(false);
  27020. scene.getOutlineRenderer().render(subMesh, batch);
  27021. engine.setColorWrite(true);
  27022. }
  27023. // Overlay
  27024. if (this.renderOverlay) {
  27025. var currentMode = engine.getAlphaMode();
  27026. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27027. scene.getOutlineRenderer().render(subMesh, batch, true);
  27028. engine.setAlphaMode(currentMode);
  27029. }
  27030. this.onAfterRenderObservable.notifyObservers(this);
  27031. return this;
  27032. };
  27033. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27034. if (isInstance && effectiveMaterial) {
  27035. effectiveMaterial.bindOnlyWorldMatrix(world);
  27036. }
  27037. };
  27038. /**
  27039. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27040. */
  27041. Mesh.prototype.getEmittedParticleSystems = function () {
  27042. var results = new Array();
  27043. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27044. var particleSystem = this.getScene().particleSystems[index];
  27045. if (particleSystem.emitter === this) {
  27046. results.push(particleSystem);
  27047. }
  27048. }
  27049. return results;
  27050. };
  27051. /**
  27052. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27053. */
  27054. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27055. var results = new Array();
  27056. var descendants = this.getDescendants();
  27057. descendants.push(this);
  27058. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27059. var particleSystem = this.getScene().particleSystems[index];
  27060. var emitter = particleSystem.emitter;
  27061. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27062. results.push(particleSystem);
  27063. }
  27064. }
  27065. return results;
  27066. };
  27067. Mesh.prototype._checkDelayState = function () {
  27068. var scene = this.getScene();
  27069. if (this._geometry) {
  27070. this._geometry.load(scene);
  27071. }
  27072. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27074. this._queueLoad(scene);
  27075. }
  27076. return this;
  27077. };
  27078. Mesh.prototype._queueLoad = function (scene) {
  27079. var _this = this;
  27080. scene._addPendingData(this);
  27081. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27082. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27083. if (data instanceof ArrayBuffer) {
  27084. _this._delayLoadingFunction(data, _this);
  27085. }
  27086. else {
  27087. _this._delayLoadingFunction(JSON.parse(data), _this);
  27088. }
  27089. _this.instances.forEach(function (instance) {
  27090. instance._syncSubMeshes();
  27091. });
  27092. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27093. scene._removePendingData(_this);
  27094. }, function () { }, scene.database, getBinaryData);
  27095. return this;
  27096. };
  27097. /**
  27098. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27099. */
  27100. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27101. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27102. return false;
  27103. }
  27104. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27105. return false;
  27106. }
  27107. this._checkDelayState();
  27108. return true;
  27109. };
  27110. /**
  27111. * Sets the mesh material by the material or multiMaterial `id` property.
  27112. * The material `id` is a string identifying the material or the multiMaterial.
  27113. * This method returns the Mesh.
  27114. */
  27115. Mesh.prototype.setMaterialByID = function (id) {
  27116. var materials = this.getScene().materials;
  27117. var index;
  27118. for (index = materials.length - 1; index > -1; index--) {
  27119. if (materials[index].id === id) {
  27120. this.material = materials[index];
  27121. return this;
  27122. }
  27123. }
  27124. // Multi
  27125. var multiMaterials = this.getScene().multiMaterials;
  27126. for (index = multiMaterials.length - 1; index > -1; index--) {
  27127. if (multiMaterials[index].id === id) {
  27128. this.material = multiMaterials[index];
  27129. return this;
  27130. }
  27131. }
  27132. return this;
  27133. };
  27134. /**
  27135. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27136. */
  27137. Mesh.prototype.getAnimatables = function () {
  27138. var results = new Array();
  27139. if (this.material) {
  27140. results.push(this.material);
  27141. }
  27142. if (this.skeleton) {
  27143. results.push(this.skeleton);
  27144. }
  27145. return results;
  27146. };
  27147. /**
  27148. * Modifies the mesh geometry according to the passed transformation matrix.
  27149. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27150. * The mesh normals are modified accordingly the same transformation.
  27151. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27152. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27153. * Returns the Mesh.
  27154. */
  27155. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27156. // Position
  27157. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27158. return this;
  27159. }
  27160. var submeshes = this.subMeshes.splice(0);
  27161. this._resetPointsArrayCache();
  27162. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27163. var temp = new Array();
  27164. var index;
  27165. for (index = 0; index < data.length; index += 3) {
  27166. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27167. }
  27168. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27169. // Normals
  27170. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27171. return this;
  27172. }
  27173. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27174. temp = [];
  27175. for (index = 0; index < data.length; index += 3) {
  27176. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27177. }
  27178. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27179. // flip faces?
  27180. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27181. this.flipFaces();
  27182. }
  27183. // Restore submeshes
  27184. this.releaseSubMeshes();
  27185. this.subMeshes = submeshes;
  27186. return this;
  27187. };
  27188. /**
  27189. * Modifies the mesh geometry according to its own current World Matrix.
  27190. * The mesh World Matrix is then reset.
  27191. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27192. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27193. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27194. * Returns the Mesh.
  27195. */
  27196. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27197. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27198. this.scaling.copyFromFloats(1, 1, 1);
  27199. this.position.copyFromFloats(0, 0, 0);
  27200. this.rotation.copyFromFloats(0, 0, 0);
  27201. //only if quaternion is already set
  27202. if (this.rotationQuaternion) {
  27203. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27204. }
  27205. this._worldMatrix = BABYLON.Matrix.Identity();
  27206. return this;
  27207. };
  27208. Object.defineProperty(Mesh.prototype, "_positions", {
  27209. // Cache
  27210. get: function () {
  27211. if (this._geometry) {
  27212. return this._geometry._positions;
  27213. }
  27214. return null;
  27215. },
  27216. enumerable: true,
  27217. configurable: true
  27218. });
  27219. Mesh.prototype._resetPointsArrayCache = function () {
  27220. if (this._geometry) {
  27221. this._geometry._resetPointsArrayCache();
  27222. }
  27223. return this;
  27224. };
  27225. Mesh.prototype._generatePointsArray = function () {
  27226. if (this._geometry) {
  27227. return this._geometry._generatePointsArray();
  27228. }
  27229. return false;
  27230. };
  27231. /**
  27232. * Returns a new Mesh object generated from the current mesh properties.
  27233. * This method must not get confused with createInstance().
  27234. * The parameter `name` is a string, the name given to the new mesh.
  27235. * The optional parameter `newParent` can be any Node object (default `null`).
  27236. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27237. * 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.
  27238. */
  27239. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27240. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27241. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27242. };
  27243. /**
  27244. * Disposes the Mesh.
  27245. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27246. * Returns nothing.
  27247. */
  27248. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27249. var _this = this;
  27250. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27251. this.morphTargetManager = null;
  27252. if (this._geometry) {
  27253. this._geometry.releaseForMesh(this, true);
  27254. }
  27255. // Sources
  27256. var meshes = this.getScene().meshes;
  27257. meshes.forEach(function (abstractMesh) {
  27258. var mesh = abstractMesh;
  27259. if (mesh._source && mesh._source === _this) {
  27260. mesh._source = null;
  27261. }
  27262. });
  27263. this._source = null;
  27264. // Instances
  27265. if (this._instancesBuffer) {
  27266. this._instancesBuffer.dispose();
  27267. this._instancesBuffer = null;
  27268. }
  27269. while (this.instances.length) {
  27270. this.instances[0].dispose();
  27271. }
  27272. // Highlight layers.
  27273. var highlightLayers = this.getScene().highlightLayers;
  27274. for (var i = 0; i < highlightLayers.length; i++) {
  27275. var highlightLayer = highlightLayers[i];
  27276. if (highlightLayer) {
  27277. highlightLayer.removeMesh(this);
  27278. highlightLayer.removeExcludedMesh(this);
  27279. }
  27280. }
  27281. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27282. };
  27283. /**
  27284. * Modifies the mesh geometry according to a displacement map.
  27285. * 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.
  27286. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27287. * This method returns nothing.
  27288. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27289. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27290. * 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.
  27291. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27292. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27293. *
  27294. * Returns the Mesh.
  27295. */
  27296. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27297. var _this = this;
  27298. var scene = this.getScene();
  27299. var onload = function (img) {
  27300. // Getting height map data
  27301. var canvas = document.createElement("canvas");
  27302. var context = canvas.getContext("2d");
  27303. var heightMapWidth = img.width;
  27304. var heightMapHeight = img.height;
  27305. canvas.width = heightMapWidth;
  27306. canvas.height = heightMapHeight;
  27307. context.drawImage(img, 0, 0);
  27308. // Create VertexData from map data
  27309. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27310. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  27311. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  27312. //execute success callback, if set
  27313. if (onSuccess) {
  27314. onSuccess(_this);
  27315. }
  27316. };
  27317. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27318. return this;
  27319. };
  27320. /**
  27321. * Modifies the mesh geometry according to a displacementMap buffer.
  27322. * 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.
  27323. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27324. * This method returns nothing.
  27325. * 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.
  27326. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  27327. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27328. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27329. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27330. *
  27331. * Returns the Mesh.
  27332. */
  27333. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  27334. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  27335. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  27336. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27337. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  27338. return this;
  27339. }
  27340. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27341. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27342. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27343. var position = BABYLON.Vector3.Zero();
  27344. var normal = BABYLON.Vector3.Zero();
  27345. var uv = BABYLON.Vector2.Zero();
  27346. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  27347. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  27348. for (var index = 0; index < positions.length; index += 3) {
  27349. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  27350. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  27351. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  27352. // Compute height
  27353. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  27354. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  27355. var pos = (u + v * heightMapWidth) * 4;
  27356. var r = buffer[pos] / 255.0;
  27357. var g = buffer[pos + 1] / 255.0;
  27358. var b = buffer[pos + 2] / 255.0;
  27359. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27360. normal.normalize();
  27361. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  27362. position = position.add(normal);
  27363. position.toArray(positions, index);
  27364. }
  27365. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  27366. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  27367. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  27368. return this;
  27369. };
  27370. /**
  27371. * Modify the mesh to get a flat shading rendering.
  27372. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  27373. * This method returns the Mesh.
  27374. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  27375. */
  27376. Mesh.prototype.convertToFlatShadedMesh = function () {
  27377. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  27378. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27379. var kinds = this.getVerticesDataKinds();
  27380. var vbs = {};
  27381. var data = {};
  27382. var newdata = {};
  27383. var updatableNormals = false;
  27384. var kindIndex;
  27385. var kind;
  27386. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27387. kind = kinds[kindIndex];
  27388. var vertexBuffer = this.getVertexBuffer(kind);
  27389. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27390. updatableNormals = vertexBuffer.isUpdatable();
  27391. kinds.splice(kindIndex, 1);
  27392. kindIndex--;
  27393. continue;
  27394. }
  27395. vbs[kind] = vertexBuffer;
  27396. data[kind] = vbs[kind].getData();
  27397. newdata[kind] = [];
  27398. }
  27399. // Save previous submeshes
  27400. var previousSubmeshes = this.subMeshes.slice(0);
  27401. var indices = this.getIndices();
  27402. var totalIndices = this.getTotalIndices();
  27403. // Generating unique vertices per face
  27404. var index;
  27405. for (index = 0; index < totalIndices; index++) {
  27406. var vertexIndex = indices[index];
  27407. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27408. kind = kinds[kindIndex];
  27409. var stride = vbs[kind].getStrideSize();
  27410. for (var offset = 0; offset < stride; offset++) {
  27411. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27412. }
  27413. }
  27414. }
  27415. // Updating faces & normal
  27416. var normals = [];
  27417. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27418. for (index = 0; index < totalIndices; index += 3) {
  27419. indices[index] = index;
  27420. indices[index + 1] = index + 1;
  27421. indices[index + 2] = index + 2;
  27422. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27423. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27424. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27425. var p1p2 = p1.subtract(p2);
  27426. var p3p2 = p3.subtract(p2);
  27427. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27428. // Store same normals for every vertex
  27429. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27430. normals.push(normal.x);
  27431. normals.push(normal.y);
  27432. normals.push(normal.z);
  27433. }
  27434. }
  27435. this.setIndices(indices);
  27436. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27437. // Updating vertex buffers
  27438. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27439. kind = kinds[kindIndex];
  27440. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27441. }
  27442. // Updating submeshes
  27443. this.releaseSubMeshes();
  27444. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27445. var previousOne = previousSubmeshes[submeshIndex];
  27446. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27447. }
  27448. this.synchronizeInstances();
  27449. return this;
  27450. };
  27451. /**
  27452. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27453. * In other words, more vertices, no more indices and a single bigger VBO.
  27454. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27455. * Returns the Mesh.
  27456. */
  27457. Mesh.prototype.convertToUnIndexedMesh = function () {
  27458. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27459. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27460. var kinds = this.getVerticesDataKinds();
  27461. var vbs = {};
  27462. var data = {};
  27463. var newdata = {};
  27464. var kindIndex;
  27465. var kind;
  27466. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27467. kind = kinds[kindIndex];
  27468. var vertexBuffer = this.getVertexBuffer(kind);
  27469. vbs[kind] = vertexBuffer;
  27470. data[kind] = vbs[kind].getData();
  27471. newdata[kind] = [];
  27472. }
  27473. // Save previous submeshes
  27474. var previousSubmeshes = this.subMeshes.slice(0);
  27475. var indices = this.getIndices();
  27476. var totalIndices = this.getTotalIndices();
  27477. // Generating unique vertices per face
  27478. var index;
  27479. for (index = 0; index < totalIndices; index++) {
  27480. var vertexIndex = indices[index];
  27481. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27482. kind = kinds[kindIndex];
  27483. var stride = vbs[kind].getStrideSize();
  27484. for (var offset = 0; offset < stride; offset++) {
  27485. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27486. }
  27487. }
  27488. }
  27489. // Updating indices
  27490. for (index = 0; index < totalIndices; index += 3) {
  27491. indices[index] = index;
  27492. indices[index + 1] = index + 1;
  27493. indices[index + 2] = index + 2;
  27494. }
  27495. this.setIndices(indices);
  27496. // Updating vertex buffers
  27497. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27498. kind = kinds[kindIndex];
  27499. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27500. }
  27501. // Updating submeshes
  27502. this.releaseSubMeshes();
  27503. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27504. var previousOne = previousSubmeshes[submeshIndex];
  27505. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27506. }
  27507. this._unIndexed = true;
  27508. this.synchronizeInstances();
  27509. return this;
  27510. };
  27511. /**
  27512. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27513. * This method returns the Mesh.
  27514. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27515. */
  27516. Mesh.prototype.flipFaces = function (flipNormals) {
  27517. if (flipNormals === void 0) { flipNormals = false; }
  27518. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27519. var i;
  27520. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27521. for (i = 0; i < vertex_data.normals.length; i++) {
  27522. vertex_data.normals[i] *= -1;
  27523. }
  27524. }
  27525. if (vertex_data.indices) {
  27526. var temp;
  27527. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27528. // reassign indices
  27529. temp = vertex_data.indices[i + 1];
  27530. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27531. vertex_data.indices[i + 2] = temp;
  27532. }
  27533. }
  27534. vertex_data.applyToMesh(this);
  27535. return this;
  27536. };
  27537. // Instances
  27538. /**
  27539. * Creates a new InstancedMesh object from the mesh model.
  27540. * An instance shares the same properties and the same material than its model.
  27541. * Only these properties of each instance can then be set individually :
  27542. * - position
  27543. * - rotation
  27544. * - rotationQuaternion
  27545. * - setPivotMatrix
  27546. * - scaling
  27547. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27548. * Warning : this method is not supported for Line mesh and LineSystem
  27549. */
  27550. Mesh.prototype.createInstance = function (name) {
  27551. return new BABYLON.InstancedMesh(name, this);
  27552. };
  27553. /**
  27554. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27555. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27556. * This method returns the Mesh.
  27557. */
  27558. Mesh.prototype.synchronizeInstances = function () {
  27559. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27560. var instance = this.instances[instanceIndex];
  27561. instance._syncSubMeshes();
  27562. }
  27563. return this;
  27564. };
  27565. /**
  27566. * Simplify the mesh according to the given array of settings.
  27567. * Function will return immediately and will simplify async. It returns the Mesh.
  27568. * @param settings a collection of simplification settings.
  27569. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27570. * @param type the type of simplification to run.
  27571. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27572. */
  27573. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27574. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27575. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27576. this.getScene().simplificationQueue.addTask({
  27577. settings: settings,
  27578. parallelProcessing: parallelProcessing,
  27579. mesh: this,
  27580. simplificationType: simplificationType,
  27581. successCallback: successCallback
  27582. });
  27583. return this;
  27584. };
  27585. /**
  27586. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27587. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27588. * This should be used together with the simplification to avoid disappearing triangles.
  27589. * Returns the Mesh.
  27590. * @param successCallback an optional success callback to be called after the optimization finished.
  27591. */
  27592. Mesh.prototype.optimizeIndices = function (successCallback) {
  27593. var _this = this;
  27594. var indices = this.getIndices();
  27595. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27596. if (!positions || !indices) {
  27597. return this;
  27598. }
  27599. var vectorPositions = new Array();
  27600. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27601. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27602. }
  27603. var dupes = new Array();
  27604. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27605. var realPos = vectorPositions.length - 1 - iteration;
  27606. var testedPosition = vectorPositions[realPos];
  27607. for (var j = 0; j < realPos; ++j) {
  27608. var againstPosition = vectorPositions[j];
  27609. if (testedPosition.equals(againstPosition)) {
  27610. dupes[realPos] = j;
  27611. break;
  27612. }
  27613. }
  27614. }, function () {
  27615. for (var i = 0; i < indices.length; ++i) {
  27616. indices[i] = dupes[indices[i]] || indices[i];
  27617. }
  27618. //indices are now reordered
  27619. var originalSubMeshes = _this.subMeshes.slice(0);
  27620. _this.setIndices(indices);
  27621. _this.subMeshes = originalSubMeshes;
  27622. if (successCallback) {
  27623. successCallback(_this);
  27624. }
  27625. });
  27626. return this;
  27627. };
  27628. Mesh.prototype.serialize = function (serializationObject) {
  27629. serializationObject.name = this.name;
  27630. serializationObject.id = this.id;
  27631. serializationObject.type = this.getClassName();
  27632. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27633. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27634. }
  27635. serializationObject.position = this.position.asArray();
  27636. if (this.rotationQuaternion) {
  27637. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27638. }
  27639. else if (this.rotation) {
  27640. serializationObject.rotation = this.rotation.asArray();
  27641. }
  27642. serializationObject.scaling = this.scaling.asArray();
  27643. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27644. serializationObject.isEnabled = this.isEnabled(false);
  27645. serializationObject.isVisible = this.isVisible;
  27646. serializationObject.infiniteDistance = this.infiniteDistance;
  27647. serializationObject.pickable = this.isPickable;
  27648. serializationObject.receiveShadows = this.receiveShadows;
  27649. serializationObject.billboardMode = this.billboardMode;
  27650. serializationObject.visibility = this.visibility;
  27651. serializationObject.checkCollisions = this.checkCollisions;
  27652. serializationObject.isBlocker = this.isBlocker;
  27653. // Parent
  27654. if (this.parent) {
  27655. serializationObject.parentId = this.parent.id;
  27656. }
  27657. // Geometry
  27658. serializationObject.isUnIndexed = this.isUnIndexed;
  27659. var geometry = this._geometry;
  27660. if (geometry) {
  27661. var geometryId = geometry.id;
  27662. serializationObject.geometryId = geometryId;
  27663. // SubMeshes
  27664. serializationObject.subMeshes = [];
  27665. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27666. var subMesh = this.subMeshes[subIndex];
  27667. serializationObject.subMeshes.push({
  27668. materialIndex: subMesh.materialIndex,
  27669. verticesStart: subMesh.verticesStart,
  27670. verticesCount: subMesh.verticesCount,
  27671. indexStart: subMesh.indexStart,
  27672. indexCount: subMesh.indexCount
  27673. });
  27674. }
  27675. }
  27676. // Material
  27677. if (this.material) {
  27678. serializationObject.materialId = this.material.id;
  27679. }
  27680. else {
  27681. this.material = null;
  27682. }
  27683. // Morph targets
  27684. if (this.morphTargetManager) {
  27685. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27686. }
  27687. // Skeleton
  27688. if (this.skeleton) {
  27689. serializationObject.skeletonId = this.skeleton.id;
  27690. }
  27691. // Physics
  27692. //TODO implement correct serialization for physics impostors.
  27693. var impostor = this.getPhysicsImpostor();
  27694. if (impostor) {
  27695. serializationObject.physicsMass = impostor.getParam("mass");
  27696. serializationObject.physicsFriction = impostor.getParam("friction");
  27697. serializationObject.physicsRestitution = impostor.getParam("mass");
  27698. serializationObject.physicsImpostor = impostor.type;
  27699. }
  27700. // Metadata
  27701. if (this.metadata) {
  27702. serializationObject.metadata = this.metadata;
  27703. }
  27704. // Instances
  27705. serializationObject.instances = [];
  27706. for (var index = 0; index < this.instances.length; index++) {
  27707. var instance = this.instances[index];
  27708. var serializationInstance = {
  27709. name: instance.name,
  27710. id: instance.id,
  27711. position: instance.position.asArray(),
  27712. scaling: instance.scaling.asArray()
  27713. };
  27714. if (instance.rotationQuaternion) {
  27715. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27716. }
  27717. else if (instance.rotation) {
  27718. serializationInstance.rotation = instance.rotation.asArray();
  27719. }
  27720. serializationObject.instances.push(serializationInstance);
  27721. // Animations
  27722. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27723. serializationInstance.ranges = instance.serializeAnimationRanges();
  27724. }
  27725. //
  27726. // Animations
  27727. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27728. serializationObject.ranges = this.serializeAnimationRanges();
  27729. // Layer mask
  27730. serializationObject.layerMask = this.layerMask;
  27731. // Alpha
  27732. serializationObject.alphaIndex = this.alphaIndex;
  27733. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27734. // Overlay
  27735. serializationObject.overlayAlpha = this.overlayAlpha;
  27736. serializationObject.overlayColor = this.overlayColor.asArray();
  27737. serializationObject.renderOverlay = this.renderOverlay;
  27738. // Fog
  27739. serializationObject.applyFog = this.applyFog;
  27740. // Action Manager
  27741. if (this.actionManager) {
  27742. serializationObject.actions = this.actionManager.serialize(this.name);
  27743. }
  27744. };
  27745. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27746. if (!this.geometry) {
  27747. return;
  27748. }
  27749. this._markSubMeshesAsAttributesDirty();
  27750. var morphTargetManager = this._morphTargetManager;
  27751. if (morphTargetManager && morphTargetManager.vertexCount) {
  27752. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27753. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27754. this.morphTargetManager = null;
  27755. return;
  27756. }
  27757. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27758. var morphTarget = morphTargetManager.getActiveTarget(index);
  27759. var positions = morphTarget.getPositions();
  27760. if (!positions) {
  27761. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27762. return;
  27763. }
  27764. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27765. var normals = morphTarget.getNormals();
  27766. if (normals) {
  27767. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27768. }
  27769. var tangents = morphTarget.getTangents();
  27770. if (tangents) {
  27771. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27772. }
  27773. }
  27774. }
  27775. else {
  27776. var index = 0;
  27777. // Positions
  27778. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27779. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27780. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27781. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27782. }
  27783. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27784. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27785. }
  27786. index++;
  27787. }
  27788. }
  27789. };
  27790. // Statics
  27791. /**
  27792. * Returns a new Mesh object parsed from the source provided.
  27793. * The parameter `parsedMesh` is the source.
  27794. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27795. */
  27796. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27797. var mesh;
  27798. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27799. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27800. }
  27801. else {
  27802. mesh = new Mesh(parsedMesh.name, scene);
  27803. }
  27804. mesh.id = parsedMesh.id;
  27805. if (BABYLON.Tags) {
  27806. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27807. }
  27808. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27809. if (parsedMesh.metadata !== undefined) {
  27810. mesh.metadata = parsedMesh.metadata;
  27811. }
  27812. if (parsedMesh.rotationQuaternion) {
  27813. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27814. }
  27815. else if (parsedMesh.rotation) {
  27816. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27817. }
  27818. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27819. if (parsedMesh.localMatrix) {
  27820. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27821. }
  27822. else if (parsedMesh.pivotMatrix) {
  27823. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27824. }
  27825. mesh.setEnabled(parsedMesh.isEnabled);
  27826. mesh.isVisible = parsedMesh.isVisible;
  27827. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27828. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27829. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27830. if (parsedMesh.applyFog !== undefined) {
  27831. mesh.applyFog = parsedMesh.applyFog;
  27832. }
  27833. if (parsedMesh.pickable !== undefined) {
  27834. mesh.isPickable = parsedMesh.pickable;
  27835. }
  27836. if (parsedMesh.alphaIndex !== undefined) {
  27837. mesh.alphaIndex = parsedMesh.alphaIndex;
  27838. }
  27839. mesh.receiveShadows = parsedMesh.receiveShadows;
  27840. mesh.billboardMode = parsedMesh.billboardMode;
  27841. if (parsedMesh.visibility !== undefined) {
  27842. mesh.visibility = parsedMesh.visibility;
  27843. }
  27844. mesh.checkCollisions = parsedMesh.checkCollisions;
  27845. if (parsedMesh.isBlocker !== undefined) {
  27846. mesh.isBlocker = parsedMesh.isBlocker;
  27847. }
  27848. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27849. // freezeWorldMatrix
  27850. if (parsedMesh.freezeWorldMatrix) {
  27851. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27852. }
  27853. // Parent
  27854. if (parsedMesh.parentId) {
  27855. mesh._waitingParentId = parsedMesh.parentId;
  27856. }
  27857. // Actions
  27858. if (parsedMesh.actions !== undefined) {
  27859. mesh._waitingActions = parsedMesh.actions;
  27860. }
  27861. // Overlay
  27862. if (parsedMesh.overlayAlpha !== undefined) {
  27863. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27864. }
  27865. if (parsedMesh.overlayColor !== undefined) {
  27866. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27867. }
  27868. if (parsedMesh.renderOverlay !== undefined) {
  27869. mesh.renderOverlay = parsedMesh.renderOverlay;
  27870. }
  27871. // Geometry
  27872. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27873. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27874. if (parsedMesh.delayLoadingFile) {
  27875. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27876. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27877. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27878. if (parsedMesh._binaryInfo) {
  27879. mesh._binaryInfo = parsedMesh._binaryInfo;
  27880. }
  27881. mesh._delayInfo = [];
  27882. if (parsedMesh.hasUVs) {
  27883. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27884. }
  27885. if (parsedMesh.hasUVs2) {
  27886. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27887. }
  27888. if (parsedMesh.hasUVs3) {
  27889. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27890. }
  27891. if (parsedMesh.hasUVs4) {
  27892. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27893. }
  27894. if (parsedMesh.hasUVs5) {
  27895. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27896. }
  27897. if (parsedMesh.hasUVs6) {
  27898. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27899. }
  27900. if (parsedMesh.hasColors) {
  27901. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27902. }
  27903. if (parsedMesh.hasMatricesIndices) {
  27904. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27905. }
  27906. if (parsedMesh.hasMatricesWeights) {
  27907. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27908. }
  27909. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27910. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27911. mesh._checkDelayState();
  27912. }
  27913. }
  27914. else {
  27915. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27916. }
  27917. // Material
  27918. if (parsedMesh.materialId) {
  27919. mesh.setMaterialByID(parsedMesh.materialId);
  27920. }
  27921. else {
  27922. mesh.material = null;
  27923. }
  27924. // Morph targets
  27925. if (parsedMesh.morphTargetManagerId > -1) {
  27926. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27927. }
  27928. // Skeleton
  27929. if (parsedMesh.skeletonId > -1) {
  27930. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27931. if (parsedMesh.numBoneInfluencers) {
  27932. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27933. }
  27934. }
  27935. // Animations
  27936. if (parsedMesh.animations) {
  27937. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27938. var parsedAnimation = parsedMesh.animations[animationIndex];
  27939. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27940. }
  27941. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27942. }
  27943. if (parsedMesh.autoAnimate) {
  27944. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27945. }
  27946. // Layer Mask
  27947. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27948. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27949. }
  27950. else {
  27951. mesh.layerMask = 0x0FFFFFFF;
  27952. }
  27953. // Physics
  27954. if (parsedMesh.physicsImpostor) {
  27955. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27956. mass: parsedMesh.physicsMass,
  27957. friction: parsedMesh.physicsFriction,
  27958. restitution: parsedMesh.physicsRestitution
  27959. }, scene);
  27960. }
  27961. // Instances
  27962. if (parsedMesh.instances) {
  27963. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27964. var parsedInstance = parsedMesh.instances[index];
  27965. var instance = mesh.createInstance(parsedInstance.name);
  27966. if (parsedInstance.id) {
  27967. instance.id = parsedInstance.id;
  27968. }
  27969. if (BABYLON.Tags) {
  27970. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27971. }
  27972. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27973. if (parsedInstance.parentId) {
  27974. instance._waitingParentId = parsedInstance.parentId;
  27975. }
  27976. if (parsedInstance.rotationQuaternion) {
  27977. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27978. }
  27979. else if (parsedInstance.rotation) {
  27980. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27981. }
  27982. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27983. instance.checkCollisions = mesh.checkCollisions;
  27984. if (parsedMesh.animations) {
  27985. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27986. parsedAnimation = parsedMesh.animations[animationIndex];
  27987. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27988. }
  27989. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27990. }
  27991. }
  27992. }
  27993. return mesh;
  27994. };
  27995. /**
  27996. * Creates a ribbon mesh.
  27997. * Please consider using the same method from the MeshBuilder class instead.
  27998. * 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.
  27999. *
  28000. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28001. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28002. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28003. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28004. * 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.
  28005. * 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.
  28006. * 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
  28007. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28008. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28010. */
  28011. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28012. if (closeArray === void 0) { closeArray = false; }
  28013. if (updatable === void 0) { updatable = false; }
  28014. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28015. pathArray: pathArray,
  28016. closeArray: closeArray,
  28017. closePath: closePath,
  28018. offset: offset,
  28019. updatable: updatable,
  28020. sideOrientation: sideOrientation,
  28021. instance: instance
  28022. }, scene);
  28023. };
  28024. /**
  28025. * Creates a plane polygonal mesh. By default, this is a disc.
  28026. * Please consider using the same method from the MeshBuilder class instead.
  28027. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28028. * 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.
  28029. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28030. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28032. */
  28033. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28034. if (scene === void 0) { scene = null; }
  28035. var options = {
  28036. radius: radius,
  28037. tessellation: tessellation,
  28038. sideOrientation: sideOrientation,
  28039. updatable: updatable
  28040. };
  28041. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28042. };
  28043. /**
  28044. * Creates a box mesh.
  28045. * Please consider using the same method from the MeshBuilder class instead.
  28046. * The parameter `size` sets the size (float) of each box side (default 1).
  28047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28048. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28050. */
  28051. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28052. if (scene === void 0) { scene = null; }
  28053. var options = {
  28054. size: size,
  28055. sideOrientation: sideOrientation,
  28056. updatable: updatable
  28057. };
  28058. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28059. };
  28060. /**
  28061. * Creates a sphere mesh.
  28062. * Please consider using the same method from the MeshBuilder class instead.
  28063. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28064. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28065. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28066. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28067. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28068. */
  28069. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28070. var options = {
  28071. segments: segments,
  28072. diameterX: diameter,
  28073. diameterY: diameter,
  28074. diameterZ: diameter,
  28075. sideOrientation: sideOrientation,
  28076. updatable: updatable
  28077. };
  28078. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28079. };
  28080. /**
  28081. * Creates a cylinder or a cone mesh.
  28082. * Please consider using the same method from the MeshBuilder class instead.
  28083. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28084. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28085. * 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.
  28086. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28087. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28088. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28089. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28091. */
  28092. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28093. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28094. if (scene !== undefined) {
  28095. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28096. updatable = scene;
  28097. }
  28098. scene = subdivisions;
  28099. subdivisions = 1;
  28100. }
  28101. var options = {
  28102. height: height,
  28103. diameterTop: diameterTop,
  28104. diameterBottom: diameterBottom,
  28105. tessellation: tessellation,
  28106. subdivisions: subdivisions,
  28107. sideOrientation: sideOrientation,
  28108. updatable: updatable
  28109. };
  28110. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28111. };
  28112. // Torus (Code from SharpDX.org)
  28113. /**
  28114. * Creates a torus mesh.
  28115. * Please consider using the same method from the MeshBuilder class instead.
  28116. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28117. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28118. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28119. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28120. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28121. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28122. */
  28123. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28124. var options = {
  28125. diameter: diameter,
  28126. thickness: thickness,
  28127. tessellation: tessellation,
  28128. sideOrientation: sideOrientation,
  28129. updatable: updatable
  28130. };
  28131. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28132. };
  28133. /**
  28134. * Creates a torus knot mesh.
  28135. * Please consider using the same method from the MeshBuilder class instead.
  28136. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28137. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28138. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28139. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28140. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28141. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28142. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28143. */
  28144. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28145. var options = {
  28146. radius: radius,
  28147. tube: tube,
  28148. radialSegments: radialSegments,
  28149. tubularSegments: tubularSegments,
  28150. p: p,
  28151. q: q,
  28152. sideOrientation: sideOrientation,
  28153. updatable: updatable
  28154. };
  28155. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28156. };
  28157. /**
  28158. * Creates a line mesh.
  28159. * Please consider using the same method from the MeshBuilder class instead.
  28160. * 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.
  28161. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28162. * The parameter `points` is an array successive Vector3.
  28163. * 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
  28164. * When updating an instance, remember that only point positions can change, not the number of points.
  28165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28166. */
  28167. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28168. if (scene === void 0) { scene = null; }
  28169. if (updatable === void 0) { updatable = false; }
  28170. if (instance === void 0) { instance = null; }
  28171. var options = {
  28172. points: points,
  28173. updatable: updatable,
  28174. instance: instance
  28175. };
  28176. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28177. };
  28178. /**
  28179. * Creates a dashed line mesh.
  28180. * Please consider using the same method from the MeshBuilder class instead.
  28181. * 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.
  28182. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28183. * The parameter `points` is an array successive Vector3.
  28184. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28185. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28186. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28187. * 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
  28188. * When updating an instance, remember that only point positions can change, not the number of points.
  28189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28190. */
  28191. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28192. if (scene === void 0) { scene = null; }
  28193. var options = {
  28194. points: points,
  28195. dashSize: dashSize,
  28196. gapSize: gapSize,
  28197. dashNb: dashNb,
  28198. updatable: updatable,
  28199. instance: instance
  28200. };
  28201. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28202. };
  28203. /**
  28204. * Creates a polygon mesh.
  28205. * Please consider using the same method from the MeshBuilder class instead.
  28206. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28207. * 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.
  28208. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28210. * Remember you can only change the shape positions, not their number when updating a polygon.
  28211. */
  28212. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28213. var options = {
  28214. shape: shape,
  28215. holes: holes,
  28216. updatable: updatable,
  28217. sideOrientation: sideOrientation
  28218. };
  28219. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28220. };
  28221. /**
  28222. * Creates an extruded polygon mesh, with depth in the Y direction.
  28223. * Please consider using the same method from the MeshBuilder class instead.
  28224. */
  28225. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28226. var options = {
  28227. shape: shape,
  28228. holes: holes,
  28229. depth: depth,
  28230. updatable: updatable,
  28231. sideOrientation: sideOrientation
  28232. };
  28233. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28234. };
  28235. /**
  28236. * Creates an extruded shape mesh.
  28237. * 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.
  28238. * Please consider using the same method from the MeshBuilder class instead.
  28239. *
  28240. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28241. * 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
  28242. * extruded along the Z axis.
  28243. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28244. * 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.
  28245. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28246. * 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
  28247. * 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
  28248. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28249. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28250. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28252. */
  28253. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28254. if (scene === void 0) { scene = null; }
  28255. var options = {
  28256. shape: shape,
  28257. path: path,
  28258. scale: scale,
  28259. rotation: rotation,
  28260. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28261. sideOrientation: sideOrientation,
  28262. instance: instance,
  28263. updatable: updatable
  28264. };
  28265. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28266. };
  28267. /**
  28268. * Creates an custom extruded shape mesh.
  28269. * 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.
  28270. * Please consider using the same method from the MeshBuilder class instead.
  28271. *
  28272. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28273. * 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
  28274. * extruded along the Z axis.
  28275. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28276. * 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
  28277. * and the distance of this point from the begining of the path :
  28278. * ```javascript
  28279. * var rotationFunction = function(i, distance) {
  28280. * // do things
  28281. * return rotationValue; }
  28282. * ```
  28283. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28284. * 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
  28285. * and the distance of this point from the begining of the path :
  28286. * ```javascript
  28287. * var scaleFunction = function(i, distance) {
  28288. * // do things
  28289. * return scaleValue;}
  28290. * ```
  28291. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28292. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28293. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28294. * 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
  28295. * 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
  28296. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28297. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28298. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28300. */
  28301. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  28302. var options = {
  28303. shape: shape,
  28304. path: path,
  28305. scaleFunction: scaleFunction,
  28306. rotationFunction: rotationFunction,
  28307. ribbonCloseArray: ribbonCloseArray,
  28308. ribbonClosePath: ribbonClosePath,
  28309. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28310. sideOrientation: sideOrientation,
  28311. instance: instance,
  28312. updatable: updatable
  28313. };
  28314. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  28315. };
  28316. /**
  28317. * Creates lathe mesh.
  28318. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  28319. * Please consider using the same method from the MeshBuilder class instead.
  28320. * 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
  28321. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  28322. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  28323. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  28324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28327. */
  28328. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  28329. var options = {
  28330. shape: shape,
  28331. radius: radius,
  28332. tessellation: tessellation,
  28333. sideOrientation: sideOrientation,
  28334. updatable: updatable
  28335. };
  28336. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  28337. };
  28338. /**
  28339. * Creates a plane mesh.
  28340. * Please consider using the same method from the MeshBuilder class instead.
  28341. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  28342. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28343. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28344. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28345. */
  28346. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  28347. var options = {
  28348. size: size,
  28349. width: size,
  28350. height: size,
  28351. sideOrientation: sideOrientation,
  28352. updatable: updatable
  28353. };
  28354. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  28355. };
  28356. /**
  28357. * Creates a ground mesh.
  28358. * Please consider using the same method from the MeshBuilder class instead.
  28359. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  28360. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  28361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28362. */
  28363. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  28364. var options = {
  28365. width: width,
  28366. height: height,
  28367. subdivisions: subdivisions,
  28368. updatable: updatable
  28369. };
  28370. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  28371. };
  28372. /**
  28373. * Creates a tiled ground mesh.
  28374. * Please consider using the same method from the MeshBuilder class instead.
  28375. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  28376. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  28377. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  28378. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  28379. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  28380. * numbers of subdivisions on the ground width and height of each tile.
  28381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28382. */
  28383. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  28384. var options = {
  28385. xmin: xmin,
  28386. zmin: zmin,
  28387. xmax: xmax,
  28388. zmax: zmax,
  28389. subdivisions: subdivisions,
  28390. precision: precision,
  28391. updatable: updatable
  28392. };
  28393. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28394. };
  28395. /**
  28396. * Creates a ground mesh from a height map.
  28397. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28398. * Please consider using the same method from the MeshBuilder class instead.
  28399. * The parameter `url` sets the URL of the height map image resource.
  28400. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28401. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28402. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28403. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28404. * 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).
  28405. * This function is passed the newly built mesh :
  28406. * ```javascript
  28407. * function(mesh) { // do things
  28408. * return; }
  28409. * ```
  28410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28411. */
  28412. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28413. var options = {
  28414. width: width,
  28415. height: height,
  28416. subdivisions: subdivisions,
  28417. minHeight: minHeight,
  28418. maxHeight: maxHeight,
  28419. updatable: updatable,
  28420. onReady: onReady
  28421. };
  28422. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28423. };
  28424. /**
  28425. * Creates a tube mesh.
  28426. * 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.
  28427. * Please consider using the same method from the MeshBuilder class instead.
  28428. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28429. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28430. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28431. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28432. * 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.
  28433. * It must return a radius value (positive float) :
  28434. * ```javascript
  28435. * var radiusFunction = function(i, distance) {
  28436. * // do things
  28437. * return radius; }
  28438. * ```
  28439. * 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
  28440. * 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
  28441. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28442. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28443. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28444. */
  28445. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28446. var options = {
  28447. path: path,
  28448. radius: radius,
  28449. tessellation: tessellation,
  28450. radiusFunction: radiusFunction,
  28451. arc: 1,
  28452. cap: cap,
  28453. updatable: updatable,
  28454. sideOrientation: sideOrientation,
  28455. instance: instance
  28456. };
  28457. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28458. };
  28459. /**
  28460. * Creates a polyhedron mesh.
  28461. * Please consider using the same method from the MeshBuilder class instead.
  28462. * 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
  28463. * to choose the wanted type.
  28464. * The parameter `size` (positive float, default 1) sets the polygon size.
  28465. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28466. * 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`.
  28467. * 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
  28468. * 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)`).
  28469. * 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
  28470. * 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.
  28471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28474. */
  28475. Mesh.CreatePolyhedron = function (name, options, scene) {
  28476. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28477. };
  28478. /**
  28479. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28480. * Please consider using the same method from the MeshBuilder class instead.
  28481. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28482. * 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`).
  28483. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28484. * 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.
  28485. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28486. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28487. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28488. */
  28489. Mesh.CreateIcoSphere = function (name, options, scene) {
  28490. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28491. };
  28492. /**
  28493. * Creates a decal mesh.
  28494. * Please consider using the same method from the MeshBuilder class instead.
  28495. * 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.
  28496. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28497. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28498. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28499. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28500. */
  28501. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28502. var options = {
  28503. position: position,
  28504. normal: normal,
  28505. size: size,
  28506. angle: angle
  28507. };
  28508. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28509. };
  28510. // Skeletons
  28511. /**
  28512. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28513. */
  28514. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28515. if (!this._sourcePositions) {
  28516. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28517. if (!source) {
  28518. return this._sourcePositions;
  28519. }
  28520. this._sourcePositions = new Float32Array(source);
  28521. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28522. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28523. }
  28524. }
  28525. return this._sourcePositions;
  28526. };
  28527. /**
  28528. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28529. */
  28530. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28531. if (!this._sourceNormals) {
  28532. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28533. if (!source) {
  28534. return this._sourceNormals;
  28535. }
  28536. this._sourceNormals = new Float32Array(source);
  28537. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28538. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28539. }
  28540. }
  28541. return this._sourceNormals;
  28542. };
  28543. /**
  28544. * Updates the vertex buffer by applying transformation from the bones.
  28545. * Returns the Mesh.
  28546. *
  28547. * @param {skeleton} skeleton to apply
  28548. */
  28549. Mesh.prototype.applySkeleton = function (skeleton) {
  28550. if (!this.geometry) {
  28551. return this;
  28552. }
  28553. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28554. return this;
  28555. }
  28556. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28557. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28558. return this;
  28559. }
  28560. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28561. return this;
  28562. }
  28563. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28564. return this;
  28565. }
  28566. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28567. return this;
  28568. }
  28569. if (!this._sourcePositions) {
  28570. var submeshes = this.subMeshes.slice();
  28571. this.setPositionsForCPUSkinning();
  28572. this.subMeshes = submeshes;
  28573. }
  28574. if (!this._sourceNormals) {
  28575. this.setNormalsForCPUSkinning();
  28576. }
  28577. // positionsData checks for not being Float32Array will only pass at most once
  28578. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28579. if (!positionsData) {
  28580. return this;
  28581. }
  28582. if (!(positionsData instanceof Float32Array)) {
  28583. positionsData = new Float32Array(positionsData);
  28584. }
  28585. // normalsData checks for not being Float32Array will only pass at most once
  28586. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28587. if (!normalsData) {
  28588. return this;
  28589. }
  28590. if (!(normalsData instanceof Float32Array)) {
  28591. normalsData = new Float32Array(normalsData);
  28592. }
  28593. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28594. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28595. if (!matricesWeightsData || !matricesIndicesData) {
  28596. return this;
  28597. }
  28598. var needExtras = this.numBoneInfluencers > 4;
  28599. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28600. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28601. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28602. var tempVector3 = BABYLON.Vector3.Zero();
  28603. var finalMatrix = new BABYLON.Matrix();
  28604. var tempMatrix = new BABYLON.Matrix();
  28605. var matWeightIdx = 0;
  28606. var inf;
  28607. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28608. var weight;
  28609. for (inf = 0; inf < 4; inf++) {
  28610. weight = matricesWeightsData[matWeightIdx + inf];
  28611. if (weight > 0) {
  28612. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28613. finalMatrix.addToSelf(tempMatrix);
  28614. }
  28615. else
  28616. break;
  28617. }
  28618. if (needExtras) {
  28619. for (inf = 0; inf < 4; inf++) {
  28620. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28621. if (weight > 0) {
  28622. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28623. finalMatrix.addToSelf(tempMatrix);
  28624. }
  28625. else
  28626. break;
  28627. }
  28628. }
  28629. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28630. tempVector3.toArray(positionsData, index);
  28631. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28632. tempVector3.toArray(normalsData, index);
  28633. finalMatrix.reset();
  28634. }
  28635. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28636. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28637. return this;
  28638. };
  28639. // Tools
  28640. /**
  28641. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28642. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28643. */
  28644. Mesh.MinMax = function (meshes) {
  28645. var minVector = null;
  28646. var maxVector = null;
  28647. meshes.forEach(function (mesh, index, array) {
  28648. var boundingInfo = mesh.getBoundingInfo();
  28649. var boundingBox = boundingInfo.boundingBox;
  28650. if (!minVector || !maxVector) {
  28651. minVector = boundingBox.minimumWorld;
  28652. maxVector = boundingBox.maximumWorld;
  28653. }
  28654. else {
  28655. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28656. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28657. }
  28658. });
  28659. if (!minVector || !maxVector) {
  28660. return {
  28661. min: BABYLON.Vector3.Zero(),
  28662. max: BABYLON.Vector3.Zero()
  28663. };
  28664. }
  28665. return {
  28666. min: minVector,
  28667. max: maxVector
  28668. };
  28669. };
  28670. /**
  28671. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28672. */
  28673. Mesh.Center = function (meshesOrMinMaxVector) {
  28674. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28675. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28676. };
  28677. /**
  28678. * Merge the array of meshes into a single mesh for performance reasons.
  28679. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28680. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28681. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28682. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28683. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28684. */
  28685. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28686. if (disposeSource === void 0) { disposeSource = true; }
  28687. var index;
  28688. if (!allow32BitsIndices) {
  28689. var totalVertices = 0;
  28690. // Counting vertices
  28691. for (index = 0; index < meshes.length; index++) {
  28692. if (meshes[index]) {
  28693. totalVertices += meshes[index].getTotalVertices();
  28694. if (totalVertices > 65536) {
  28695. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28696. return null;
  28697. }
  28698. }
  28699. }
  28700. }
  28701. // Merge
  28702. var vertexData = null;
  28703. var otherVertexData;
  28704. var indiceArray = new Array();
  28705. var source = null;
  28706. for (index = 0; index < meshes.length; index++) {
  28707. if (meshes[index]) {
  28708. meshes[index].computeWorldMatrix(true);
  28709. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28710. otherVertexData.transform(meshes[index].getWorldMatrix());
  28711. if (vertexData) {
  28712. vertexData.merge(otherVertexData);
  28713. }
  28714. else {
  28715. vertexData = otherVertexData;
  28716. source = meshes[index];
  28717. }
  28718. if (subdivideWithSubMeshes) {
  28719. indiceArray.push(meshes[index].getTotalIndices());
  28720. }
  28721. }
  28722. }
  28723. source = source;
  28724. if (!meshSubclass) {
  28725. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28726. }
  28727. vertexData.applyToMesh(meshSubclass);
  28728. // Setting properties
  28729. meshSubclass.material = source.material;
  28730. meshSubclass.checkCollisions = source.checkCollisions;
  28731. // Cleaning
  28732. if (disposeSource) {
  28733. for (index = 0; index < meshes.length; index++) {
  28734. if (meshes[index]) {
  28735. meshes[index].dispose();
  28736. }
  28737. }
  28738. }
  28739. // Subdivide
  28740. if (subdivideWithSubMeshes) {
  28741. //-- Suppresions du submesh global
  28742. meshSubclass.releaseSubMeshes();
  28743. index = 0;
  28744. var offset = 0;
  28745. //-- aplique la subdivision en fonction du tableau d'indices
  28746. while (index < indiceArray.length) {
  28747. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28748. offset += indiceArray[index];
  28749. index++;
  28750. }
  28751. }
  28752. return meshSubclass;
  28753. };
  28754. // Consts
  28755. Mesh._FRONTSIDE = 0;
  28756. Mesh._BACKSIDE = 1;
  28757. Mesh._DOUBLESIDE = 2;
  28758. Mesh._DEFAULTSIDE = 0;
  28759. Mesh._NO_CAP = 0;
  28760. Mesh._CAP_START = 1;
  28761. Mesh._CAP_END = 2;
  28762. Mesh._CAP_ALL = 3;
  28763. return Mesh;
  28764. }(BABYLON.AbstractMesh));
  28765. BABYLON.Mesh = Mesh;
  28766. })(BABYLON || (BABYLON = {}));
  28767. //# sourceMappingURL=babylon.mesh.js.map
  28768. var BABYLON;
  28769. (function (BABYLON) {
  28770. var BaseSubMesh = /** @class */ (function () {
  28771. function BaseSubMesh() {
  28772. }
  28773. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28774. get: function () {
  28775. return this._materialEffect;
  28776. },
  28777. enumerable: true,
  28778. configurable: true
  28779. });
  28780. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28781. if (defines === void 0) { defines = null; }
  28782. if (this._materialEffect === effect) {
  28783. if (!effect) {
  28784. this._materialDefines = null;
  28785. }
  28786. return;
  28787. }
  28788. this._materialDefines = defines;
  28789. this._materialEffect = effect;
  28790. };
  28791. return BaseSubMesh;
  28792. }());
  28793. BABYLON.BaseSubMesh = BaseSubMesh;
  28794. var SubMesh = /** @class */ (function (_super) {
  28795. __extends(SubMesh, _super);
  28796. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28797. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28798. var _this = _super.call(this) || this;
  28799. _this.materialIndex = materialIndex;
  28800. _this.verticesStart = verticesStart;
  28801. _this.verticesCount = verticesCount;
  28802. _this.indexStart = indexStart;
  28803. _this.indexCount = indexCount;
  28804. _this._renderId = 0;
  28805. _this._mesh = mesh;
  28806. _this._renderingMesh = renderingMesh || mesh;
  28807. mesh.subMeshes.push(_this);
  28808. _this._trianglePlanes = [];
  28809. _this._id = mesh.subMeshes.length - 1;
  28810. if (createBoundingBox) {
  28811. _this.refreshBoundingInfo();
  28812. mesh.computeWorldMatrix(true);
  28813. }
  28814. return _this;
  28815. }
  28816. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28817. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28818. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28819. };
  28820. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28821. get: function () {
  28822. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28823. },
  28824. enumerable: true,
  28825. configurable: true
  28826. });
  28827. /**
  28828. * Returns the submesh BoudingInfo object.
  28829. */
  28830. SubMesh.prototype.getBoundingInfo = function () {
  28831. if (this.IsGlobal) {
  28832. return this._mesh.getBoundingInfo();
  28833. }
  28834. return this._boundingInfo;
  28835. };
  28836. /**
  28837. * Sets the submesh BoundingInfo.
  28838. * Return the SubMesh.
  28839. */
  28840. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28841. this._boundingInfo = boundingInfo;
  28842. return this;
  28843. };
  28844. /**
  28845. * Returns the mesh of the current submesh.
  28846. */
  28847. SubMesh.prototype.getMesh = function () {
  28848. return this._mesh;
  28849. };
  28850. /**
  28851. * Returns the rendering mesh of the submesh.
  28852. */
  28853. SubMesh.prototype.getRenderingMesh = function () {
  28854. return this._renderingMesh;
  28855. };
  28856. /**
  28857. * Returns the submesh material.
  28858. */
  28859. SubMesh.prototype.getMaterial = function () {
  28860. var rootMaterial = this._renderingMesh.material;
  28861. if (rootMaterial === null || rootMaterial === undefined) {
  28862. return this._mesh.getScene().defaultMaterial;
  28863. }
  28864. else if (rootMaterial.getSubMaterial) {
  28865. var multiMaterial = rootMaterial;
  28866. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28867. if (this._currentMaterial !== effectiveMaterial) {
  28868. this._currentMaterial = effectiveMaterial;
  28869. this._materialDefines = null;
  28870. }
  28871. return effectiveMaterial;
  28872. }
  28873. return rootMaterial;
  28874. };
  28875. // Methods
  28876. /**
  28877. * Sets a new updated BoundingInfo object to the submesh.
  28878. * Returns the SubMesh.
  28879. */
  28880. SubMesh.prototype.refreshBoundingInfo = function () {
  28881. this._lastColliderWorldVertices = null;
  28882. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28883. return this;
  28884. }
  28885. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28886. if (!data) {
  28887. this._boundingInfo = this._mesh.getBoundingInfo();
  28888. return this;
  28889. }
  28890. var indices = this._renderingMesh.getIndices();
  28891. var extend;
  28892. //is this the only submesh?
  28893. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28894. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28895. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28896. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28897. }
  28898. else {
  28899. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28900. }
  28901. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28902. return this;
  28903. };
  28904. SubMesh.prototype._checkCollision = function (collider) {
  28905. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28906. return boundingInfo._checkCollision(collider);
  28907. };
  28908. /**
  28909. * Updates the submesh BoundingInfo.
  28910. * Returns the Submesh.
  28911. */
  28912. SubMesh.prototype.updateBoundingInfo = function (world) {
  28913. var boundingInfo = this.getBoundingInfo();
  28914. if (!boundingInfo) {
  28915. this.refreshBoundingInfo();
  28916. boundingInfo = this.getBoundingInfo();
  28917. }
  28918. boundingInfo.update(world);
  28919. return this;
  28920. };
  28921. /**
  28922. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28923. * Boolean returned.
  28924. */
  28925. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28926. var boundingInfo = this.getBoundingInfo();
  28927. if (!boundingInfo) {
  28928. return false;
  28929. }
  28930. return boundingInfo.isInFrustum(frustumPlanes);
  28931. };
  28932. /**
  28933. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28934. * Boolean returned.
  28935. */
  28936. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28937. var boundingInfo = this.getBoundingInfo();
  28938. if (!boundingInfo) {
  28939. return false;
  28940. }
  28941. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28942. };
  28943. /**
  28944. * Renders the submesh.
  28945. * Returns it.
  28946. */
  28947. SubMesh.prototype.render = function (enableAlphaMode) {
  28948. this._renderingMesh.render(this, enableAlphaMode);
  28949. return this;
  28950. };
  28951. /**
  28952. * Returns a new Index Buffer.
  28953. * Type returned : WebGLBuffer.
  28954. */
  28955. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28956. if (!this._linesIndexBuffer) {
  28957. var linesIndices = [];
  28958. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28959. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28960. }
  28961. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28962. this.linesIndexCount = linesIndices.length;
  28963. }
  28964. return this._linesIndexBuffer;
  28965. };
  28966. /**
  28967. * True is the passed Ray intersects the submesh bounding box.
  28968. * Boolean returned.
  28969. */
  28970. SubMesh.prototype.canIntersects = function (ray) {
  28971. var boundingInfo = this.getBoundingInfo();
  28972. if (!boundingInfo) {
  28973. return false;
  28974. }
  28975. return ray.intersectsBox(boundingInfo.boundingBox);
  28976. };
  28977. /**
  28978. * Returns an object IntersectionInfo.
  28979. */
  28980. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28981. var intersectInfo = null;
  28982. // LineMesh first as it's also a Mesh...
  28983. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28984. var lineMesh = this._mesh;
  28985. // Line test
  28986. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28987. var p0 = positions[indices[index]];
  28988. var p1 = positions[indices[index + 1]];
  28989. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28990. if (length < 0) {
  28991. continue;
  28992. }
  28993. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28994. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28995. if (fastCheck) {
  28996. break;
  28997. }
  28998. }
  28999. }
  29000. }
  29001. else {
  29002. // Triangles test
  29003. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29004. var p0 = positions[indices[index]];
  29005. var p1 = positions[indices[index + 1]];
  29006. var p2 = positions[indices[index + 2]];
  29007. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29008. if (currentIntersectInfo) {
  29009. if (currentIntersectInfo.distance < 0) {
  29010. continue;
  29011. }
  29012. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29013. intersectInfo = currentIntersectInfo;
  29014. intersectInfo.faceId = index / 3;
  29015. if (fastCheck) {
  29016. break;
  29017. }
  29018. }
  29019. }
  29020. }
  29021. }
  29022. return intersectInfo;
  29023. };
  29024. SubMesh.prototype._rebuild = function () {
  29025. if (this._linesIndexBuffer) {
  29026. this._linesIndexBuffer = null;
  29027. }
  29028. };
  29029. // Clone
  29030. /**
  29031. * Creates a new Submesh from the passed Mesh.
  29032. */
  29033. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29034. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29035. if (!this.IsGlobal) {
  29036. var boundingInfo = this.getBoundingInfo();
  29037. if (!boundingInfo) {
  29038. return result;
  29039. }
  29040. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29041. }
  29042. return result;
  29043. };
  29044. // Dispose
  29045. /**
  29046. * Disposes the Submesh.
  29047. * Returns nothing.
  29048. */
  29049. SubMesh.prototype.dispose = function () {
  29050. if (this._linesIndexBuffer) {
  29051. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29052. this._linesIndexBuffer = null;
  29053. }
  29054. // Remove from mesh
  29055. var index = this._mesh.subMeshes.indexOf(this);
  29056. this._mesh.subMeshes.splice(index, 1);
  29057. };
  29058. // Statics
  29059. /**
  29060. * Creates a new Submesh from the passed parameters :
  29061. * - materialIndex (integer) : the index of the main mesh material.
  29062. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29063. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29064. * - mesh (Mesh) : the main mesh to create the submesh from.
  29065. * - renderingMesh (optional Mesh) : rendering mesh.
  29066. */
  29067. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29068. var minVertexIndex = Number.MAX_VALUE;
  29069. var maxVertexIndex = -Number.MAX_VALUE;
  29070. renderingMesh = (renderingMesh || mesh);
  29071. var indices = renderingMesh.getIndices();
  29072. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29073. var vertexIndex = indices[index];
  29074. if (vertexIndex < minVertexIndex)
  29075. minVertexIndex = vertexIndex;
  29076. if (vertexIndex > maxVertexIndex)
  29077. maxVertexIndex = vertexIndex;
  29078. }
  29079. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29080. };
  29081. return SubMesh;
  29082. }(BaseSubMesh));
  29083. BABYLON.SubMesh = SubMesh;
  29084. })(BABYLON || (BABYLON = {}));
  29085. //# sourceMappingURL=babylon.subMesh.js.map
  29086. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29087. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29088. s = arguments[i];
  29089. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29090. t[p] = s[p];
  29091. }
  29092. return t;
  29093. };
  29094. var BABYLON;
  29095. (function (BABYLON) {
  29096. var MaterialDefines = /** @class */ (function () {
  29097. function MaterialDefines() {
  29098. this._isDirty = true;
  29099. this._areLightsDirty = true;
  29100. this._areAttributesDirty = true;
  29101. this._areTexturesDirty = true;
  29102. this._areFresnelDirty = true;
  29103. this._areMiscDirty = true;
  29104. this._areImageProcessingDirty = true;
  29105. this._normals = false;
  29106. this._uvs = false;
  29107. this._needNormals = false;
  29108. this._needUVs = false;
  29109. }
  29110. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29111. get: function () {
  29112. return this._isDirty;
  29113. },
  29114. enumerable: true,
  29115. configurable: true
  29116. });
  29117. MaterialDefines.prototype.markAsProcessed = function () {
  29118. this._isDirty = false;
  29119. this._areAttributesDirty = false;
  29120. this._areTexturesDirty = false;
  29121. this._areFresnelDirty = false;
  29122. this._areLightsDirty = false;
  29123. this._areMiscDirty = false;
  29124. this._areImageProcessingDirty = false;
  29125. };
  29126. MaterialDefines.prototype.markAsUnprocessed = function () {
  29127. this._isDirty = true;
  29128. };
  29129. MaterialDefines.prototype.markAllAsDirty = function () {
  29130. this._areTexturesDirty = true;
  29131. this._areAttributesDirty = true;
  29132. this._areLightsDirty = true;
  29133. this._areFresnelDirty = true;
  29134. this._areMiscDirty = true;
  29135. this._areImageProcessingDirty = true;
  29136. this._isDirty = true;
  29137. };
  29138. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29139. this._areImageProcessingDirty = true;
  29140. this._isDirty = true;
  29141. };
  29142. MaterialDefines.prototype.markAsLightDirty = function () {
  29143. this._areLightsDirty = true;
  29144. this._isDirty = true;
  29145. };
  29146. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29147. this._areAttributesDirty = true;
  29148. this._isDirty = true;
  29149. };
  29150. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29151. this._areTexturesDirty = true;
  29152. this._isDirty = true;
  29153. };
  29154. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29155. this._areFresnelDirty = true;
  29156. this._isDirty = true;
  29157. };
  29158. MaterialDefines.prototype.markAsMiscDirty = function () {
  29159. this._areMiscDirty = true;
  29160. this._isDirty = true;
  29161. };
  29162. MaterialDefines.prototype.rebuild = function () {
  29163. if (this._keys) {
  29164. delete this._keys;
  29165. }
  29166. this._keys = [];
  29167. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29168. var key = _a[_i];
  29169. if (key[0] === "_") {
  29170. continue;
  29171. }
  29172. this._keys.push(key);
  29173. }
  29174. };
  29175. MaterialDefines.prototype.isEqual = function (other) {
  29176. if (this._keys.length !== other._keys.length) {
  29177. return false;
  29178. }
  29179. for (var index = 0; index < this._keys.length; index++) {
  29180. var prop = this._keys[index];
  29181. if (this[prop] !== other[prop]) {
  29182. return false;
  29183. }
  29184. }
  29185. return true;
  29186. };
  29187. MaterialDefines.prototype.cloneTo = function (other) {
  29188. if (this._keys.length !== other._keys.length) {
  29189. other._keys = this._keys.slice(0);
  29190. }
  29191. for (var index = 0; index < this._keys.length; index++) {
  29192. var prop = this._keys[index];
  29193. other[prop] = this[prop];
  29194. }
  29195. };
  29196. MaterialDefines.prototype.reset = function () {
  29197. for (var index = 0; index < this._keys.length; index++) {
  29198. var prop = this._keys[index];
  29199. if (typeof (this[prop]) === "number") {
  29200. this[prop] = 0;
  29201. }
  29202. else {
  29203. this[prop] = false;
  29204. }
  29205. }
  29206. };
  29207. MaterialDefines.prototype.toString = function () {
  29208. var result = "";
  29209. for (var index = 0; index < this._keys.length; index++) {
  29210. var prop = this._keys[index];
  29211. var value = this[prop];
  29212. if (typeof (value) === "number") {
  29213. result += "#define " + prop + " " + this[prop] + "\n";
  29214. }
  29215. else if (value) {
  29216. result += "#define " + prop + "\n";
  29217. }
  29218. }
  29219. return result;
  29220. };
  29221. return MaterialDefines;
  29222. }());
  29223. BABYLON.MaterialDefines = MaterialDefines;
  29224. var Material = /** @class */ (function () {
  29225. function Material(name, scene, doNotAdd) {
  29226. this.checkReadyOnEveryCall = false;
  29227. this.checkReadyOnlyOnce = false;
  29228. this.state = "";
  29229. this._alpha = 1.0;
  29230. this._backFaceCulling = true;
  29231. this.doNotSerialize = false;
  29232. this.storeEffectOnSubMeshes = false;
  29233. /**
  29234. * An event triggered when the material is disposed.
  29235. * @type {BABYLON.Observable}
  29236. */
  29237. this.onDisposeObservable = new BABYLON.Observable();
  29238. /**
  29239. * An event triggered when the material is bound.
  29240. * @type {BABYLON.Observable}
  29241. */
  29242. this.onBindObservable = new BABYLON.Observable();
  29243. /**
  29244. * An event triggered when the material is unbound.
  29245. * @type {BABYLON.Observable}
  29246. */
  29247. this.onUnBindObservable = new BABYLON.Observable();
  29248. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29249. this._needDepthPrePass = false;
  29250. this.disableDepthWrite = false;
  29251. this.forceDepthWrite = false;
  29252. this.separateCullingPass = false;
  29253. this._fogEnabled = true;
  29254. this.pointSize = 1.0;
  29255. this.zOffset = 0;
  29256. this._wasPreviouslyReady = false;
  29257. this._fillMode = Material.TriangleFillMode;
  29258. this.name = name;
  29259. this.id = name || BABYLON.Tools.RandomId();
  29260. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29261. if (this._scene.useRightHandedSystem) {
  29262. this.sideOrientation = Material.ClockWiseSideOrientation;
  29263. }
  29264. else {
  29265. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29266. }
  29267. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  29268. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  29269. if (!doNotAdd) {
  29270. this._scene.materials.push(this);
  29271. }
  29272. }
  29273. Object.defineProperty(Material, "TriangleFillMode", {
  29274. get: function () {
  29275. return Material._TriangleFillMode;
  29276. },
  29277. enumerable: true,
  29278. configurable: true
  29279. });
  29280. Object.defineProperty(Material, "WireFrameFillMode", {
  29281. get: function () {
  29282. return Material._WireFrameFillMode;
  29283. },
  29284. enumerable: true,
  29285. configurable: true
  29286. });
  29287. Object.defineProperty(Material, "PointFillMode", {
  29288. get: function () {
  29289. return Material._PointFillMode;
  29290. },
  29291. enumerable: true,
  29292. configurable: true
  29293. });
  29294. Object.defineProperty(Material, "PointListDrawMode", {
  29295. get: function () {
  29296. return Material._PointListDrawMode;
  29297. },
  29298. enumerable: true,
  29299. configurable: true
  29300. });
  29301. Object.defineProperty(Material, "LineListDrawMode", {
  29302. get: function () {
  29303. return Material._LineListDrawMode;
  29304. },
  29305. enumerable: true,
  29306. configurable: true
  29307. });
  29308. Object.defineProperty(Material, "LineLoopDrawMode", {
  29309. get: function () {
  29310. return Material._LineLoopDrawMode;
  29311. },
  29312. enumerable: true,
  29313. configurable: true
  29314. });
  29315. Object.defineProperty(Material, "LineStripDrawMode", {
  29316. get: function () {
  29317. return Material._LineStripDrawMode;
  29318. },
  29319. enumerable: true,
  29320. configurable: true
  29321. });
  29322. Object.defineProperty(Material, "TriangleStripDrawMode", {
  29323. get: function () {
  29324. return Material._TriangleStripDrawMode;
  29325. },
  29326. enumerable: true,
  29327. configurable: true
  29328. });
  29329. Object.defineProperty(Material, "TriangleFanDrawMode", {
  29330. get: function () {
  29331. return Material._TriangleFanDrawMode;
  29332. },
  29333. enumerable: true,
  29334. configurable: true
  29335. });
  29336. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29337. get: function () {
  29338. return Material._ClockWiseSideOrientation;
  29339. },
  29340. enumerable: true,
  29341. configurable: true
  29342. });
  29343. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29344. get: function () {
  29345. return Material._CounterClockWiseSideOrientation;
  29346. },
  29347. enumerable: true,
  29348. configurable: true
  29349. });
  29350. Object.defineProperty(Material, "TextureDirtyFlag", {
  29351. get: function () {
  29352. return Material._TextureDirtyFlag;
  29353. },
  29354. enumerable: true,
  29355. configurable: true
  29356. });
  29357. Object.defineProperty(Material, "LightDirtyFlag", {
  29358. get: function () {
  29359. return Material._LightDirtyFlag;
  29360. },
  29361. enumerable: true,
  29362. configurable: true
  29363. });
  29364. Object.defineProperty(Material, "FresnelDirtyFlag", {
  29365. get: function () {
  29366. return Material._FresnelDirtyFlag;
  29367. },
  29368. enumerable: true,
  29369. configurable: true
  29370. });
  29371. Object.defineProperty(Material, "AttributesDirtyFlag", {
  29372. get: function () {
  29373. return Material._AttributesDirtyFlag;
  29374. },
  29375. enumerable: true,
  29376. configurable: true
  29377. });
  29378. Object.defineProperty(Material, "MiscDirtyFlag", {
  29379. get: function () {
  29380. return Material._MiscDirtyFlag;
  29381. },
  29382. enumerable: true,
  29383. configurable: true
  29384. });
  29385. Object.defineProperty(Material.prototype, "alpha", {
  29386. get: function () {
  29387. return this._alpha;
  29388. },
  29389. set: function (value) {
  29390. if (this._alpha === value) {
  29391. return;
  29392. }
  29393. this._alpha = value;
  29394. this.markAsDirty(Material.MiscDirtyFlag);
  29395. },
  29396. enumerable: true,
  29397. configurable: true
  29398. });
  29399. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29400. get: function () {
  29401. return this._backFaceCulling;
  29402. },
  29403. set: function (value) {
  29404. if (this._backFaceCulling === value) {
  29405. return;
  29406. }
  29407. this._backFaceCulling = value;
  29408. this.markAsDirty(Material.TextureDirtyFlag);
  29409. },
  29410. enumerable: true,
  29411. configurable: true
  29412. });
  29413. Object.defineProperty(Material.prototype, "onDispose", {
  29414. set: function (callback) {
  29415. if (this._onDisposeObserver) {
  29416. this.onDisposeObservable.remove(this._onDisposeObserver);
  29417. }
  29418. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29419. },
  29420. enumerable: true,
  29421. configurable: true
  29422. });
  29423. Object.defineProperty(Material.prototype, "onBind", {
  29424. set: function (callback) {
  29425. if (this._onBindObserver) {
  29426. this.onBindObservable.remove(this._onBindObserver);
  29427. }
  29428. this._onBindObserver = this.onBindObservable.add(callback);
  29429. },
  29430. enumerable: true,
  29431. configurable: true
  29432. });
  29433. Object.defineProperty(Material.prototype, "alphaMode", {
  29434. get: function () {
  29435. return this._alphaMode;
  29436. },
  29437. set: function (value) {
  29438. if (this._alphaMode === value) {
  29439. return;
  29440. }
  29441. this._alphaMode = value;
  29442. this.markAsDirty(Material.TextureDirtyFlag);
  29443. },
  29444. enumerable: true,
  29445. configurable: true
  29446. });
  29447. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29448. get: function () {
  29449. return this._needDepthPrePass;
  29450. },
  29451. set: function (value) {
  29452. if (this._needDepthPrePass === value) {
  29453. return;
  29454. }
  29455. this._needDepthPrePass = value;
  29456. if (this._needDepthPrePass) {
  29457. this.checkReadyOnEveryCall = true;
  29458. }
  29459. },
  29460. enumerable: true,
  29461. configurable: true
  29462. });
  29463. Object.defineProperty(Material.prototype, "fogEnabled", {
  29464. get: function () {
  29465. return this._fogEnabled;
  29466. },
  29467. set: function (value) {
  29468. if (this._fogEnabled === value) {
  29469. return;
  29470. }
  29471. this._fogEnabled = value;
  29472. this.markAsDirty(Material.MiscDirtyFlag);
  29473. },
  29474. enumerable: true,
  29475. configurable: true
  29476. });
  29477. Object.defineProperty(Material.prototype, "wireframe", {
  29478. get: function () {
  29479. return this._fillMode === Material.WireFrameFillMode;
  29480. },
  29481. set: function (value) {
  29482. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29483. },
  29484. enumerable: true,
  29485. configurable: true
  29486. });
  29487. Object.defineProperty(Material.prototype, "pointsCloud", {
  29488. get: function () {
  29489. return this._fillMode === Material.PointFillMode;
  29490. },
  29491. set: function (value) {
  29492. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29493. },
  29494. enumerable: true,
  29495. configurable: true
  29496. });
  29497. Object.defineProperty(Material.prototype, "fillMode", {
  29498. get: function () {
  29499. return this._fillMode;
  29500. },
  29501. set: function (value) {
  29502. if (this._fillMode === value) {
  29503. return;
  29504. }
  29505. this._fillMode = value;
  29506. this.markAsDirty(Material.MiscDirtyFlag);
  29507. },
  29508. enumerable: true,
  29509. configurable: true
  29510. });
  29511. /**
  29512. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29513. * subclasses should override adding information pertainent to themselves
  29514. */
  29515. Material.prototype.toString = function (fullDetails) {
  29516. var ret = "Name: " + this.name;
  29517. if (fullDetails) {
  29518. }
  29519. return ret;
  29520. };
  29521. /**
  29522. * Child classes can use it to update shaders
  29523. */
  29524. Material.prototype.getClassName = function () {
  29525. return "Material";
  29526. };
  29527. Object.defineProperty(Material.prototype, "isFrozen", {
  29528. get: function () {
  29529. return this.checkReadyOnlyOnce;
  29530. },
  29531. enumerable: true,
  29532. configurable: true
  29533. });
  29534. Material.prototype.freeze = function () {
  29535. this.checkReadyOnlyOnce = true;
  29536. };
  29537. Material.prototype.unfreeze = function () {
  29538. this.checkReadyOnlyOnce = false;
  29539. };
  29540. Material.prototype.isReady = function (mesh, useInstances) {
  29541. return true;
  29542. };
  29543. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29544. return false;
  29545. };
  29546. Material.prototype.getEffect = function () {
  29547. return this._effect;
  29548. };
  29549. Material.prototype.getScene = function () {
  29550. return this._scene;
  29551. };
  29552. Material.prototype.needAlphaBlending = function () {
  29553. return (this.alpha < 1.0);
  29554. };
  29555. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29556. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29557. };
  29558. Material.prototype.needAlphaTesting = function () {
  29559. return false;
  29560. };
  29561. Material.prototype.getAlphaTestTexture = function () {
  29562. return null;
  29563. };
  29564. Material.prototype.markDirty = function () {
  29565. this._wasPreviouslyReady = false;
  29566. };
  29567. Material.prototype._preBind = function (effect, overrideOrientation) {
  29568. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29569. var engine = this._scene.getEngine();
  29570. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29571. var reverse = orientation === Material.ClockWiseSideOrientation;
  29572. engine.enableEffect(effect ? effect : this._effect);
  29573. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29574. return reverse;
  29575. };
  29576. Material.prototype.bind = function (world, mesh) {
  29577. };
  29578. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29579. };
  29580. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29581. };
  29582. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29583. sceneUbo.bindToEffect(effect, "Scene");
  29584. };
  29585. Material.prototype.bindView = function (effect) {
  29586. if (!this._useUBO) {
  29587. effect.setMatrix("view", this.getScene().getViewMatrix());
  29588. }
  29589. else {
  29590. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29591. }
  29592. };
  29593. Material.prototype.bindViewProjection = function (effect) {
  29594. if (!this._useUBO) {
  29595. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29596. }
  29597. else {
  29598. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29599. }
  29600. };
  29601. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29602. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29603. };
  29604. Material.prototype._afterBind = function (mesh) {
  29605. this._scene._cachedMaterial = this;
  29606. if (mesh) {
  29607. this._scene._cachedVisibility = mesh.visibility;
  29608. }
  29609. else {
  29610. this._scene._cachedVisibility = 1;
  29611. }
  29612. if (mesh) {
  29613. this.onBindObservable.notifyObservers(mesh);
  29614. }
  29615. if (this.disableDepthWrite) {
  29616. var engine = this._scene.getEngine();
  29617. this._cachedDepthWriteState = engine.getDepthWrite();
  29618. engine.setDepthWrite(false);
  29619. }
  29620. };
  29621. Material.prototype.unbind = function () {
  29622. this.onUnBindObservable.notifyObservers(this);
  29623. if (this.disableDepthWrite) {
  29624. var engine = this._scene.getEngine();
  29625. engine.setDepthWrite(this._cachedDepthWriteState);
  29626. }
  29627. };
  29628. Material.prototype.getActiveTextures = function () {
  29629. return [];
  29630. };
  29631. Material.prototype.hasTexture = function (texture) {
  29632. return false;
  29633. };
  29634. Material.prototype.clone = function (name) {
  29635. return null;
  29636. };
  29637. Material.prototype.getBindedMeshes = function () {
  29638. var result = new Array();
  29639. for (var index = 0; index < this._scene.meshes.length; index++) {
  29640. var mesh = this._scene.meshes[index];
  29641. if (mesh.material === this) {
  29642. result.push(mesh);
  29643. }
  29644. }
  29645. return result;
  29646. };
  29647. /**
  29648. * Force shader compilation including textures ready check
  29649. */
  29650. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29651. var _this = this;
  29652. var localOptions = __assign({ clipPlane: false }, options);
  29653. var subMesh = new BABYLON.BaseSubMesh();
  29654. var scene = this.getScene();
  29655. var checkReady = function () {
  29656. if (!_this._scene || !_this._scene.getEngine()) {
  29657. return;
  29658. }
  29659. if (subMesh._materialDefines) {
  29660. subMesh._materialDefines._renderId = -1;
  29661. }
  29662. var clipPlaneState = scene.clipPlane;
  29663. if (localOptions.clipPlane) {
  29664. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29665. }
  29666. if (_this.storeEffectOnSubMeshes) {
  29667. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29668. if (onCompiled) {
  29669. onCompiled(_this);
  29670. }
  29671. }
  29672. else {
  29673. setTimeout(checkReady, 16);
  29674. }
  29675. }
  29676. else {
  29677. if (_this.isReady(mesh)) {
  29678. if (onCompiled) {
  29679. onCompiled(_this);
  29680. }
  29681. }
  29682. else {
  29683. setTimeout(checkReady, 16);
  29684. }
  29685. }
  29686. if (options && options.clipPlane) {
  29687. scene.clipPlane = clipPlaneState;
  29688. }
  29689. };
  29690. checkReady();
  29691. };
  29692. Material.prototype.markAsDirty = function (flag) {
  29693. if (flag & Material.TextureDirtyFlag) {
  29694. this._markAllSubMeshesAsTexturesDirty();
  29695. }
  29696. if (flag & Material.LightDirtyFlag) {
  29697. this._markAllSubMeshesAsLightsDirty();
  29698. }
  29699. if (flag & Material.FresnelDirtyFlag) {
  29700. this._markAllSubMeshesAsFresnelDirty();
  29701. }
  29702. if (flag & Material.AttributesDirtyFlag) {
  29703. this._markAllSubMeshesAsAttributesDirty();
  29704. }
  29705. if (flag & Material.MiscDirtyFlag) {
  29706. this._markAllSubMeshesAsMiscDirty();
  29707. }
  29708. this.getScene().resetCachedMaterial();
  29709. };
  29710. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29711. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29712. var mesh = _a[_i];
  29713. if (!mesh.subMeshes) {
  29714. continue;
  29715. }
  29716. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29717. var subMesh = _c[_b];
  29718. if (subMesh.getMaterial() !== this) {
  29719. continue;
  29720. }
  29721. if (!subMesh._materialDefines) {
  29722. continue;
  29723. }
  29724. func(subMesh._materialDefines);
  29725. }
  29726. }
  29727. };
  29728. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29729. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29730. };
  29731. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29732. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29733. };
  29734. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29735. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29736. };
  29737. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29738. this._markAllSubMeshesAsDirty(function (defines) {
  29739. defines.markAsFresnelDirty();
  29740. defines.markAsMiscDirty();
  29741. });
  29742. };
  29743. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29744. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29745. };
  29746. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29747. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29748. };
  29749. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29750. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29751. };
  29752. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29753. this._markAllSubMeshesAsDirty(function (defines) {
  29754. defines.markAsTexturesDirty();
  29755. defines.markAsMiscDirty();
  29756. });
  29757. };
  29758. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29759. // Animations
  29760. this.getScene().stopAnimation(this);
  29761. // Remove from scene
  29762. var index = this._scene.materials.indexOf(this);
  29763. if (index >= 0) {
  29764. this._scene.materials.splice(index, 1);
  29765. }
  29766. // Remove from meshes
  29767. for (index = 0; index < this._scene.meshes.length; index++) {
  29768. var mesh = this._scene.meshes[index];
  29769. if (mesh.material === this) {
  29770. mesh.material = null;
  29771. if (mesh.geometry) {
  29772. var geometry = (mesh.geometry);
  29773. if (this.storeEffectOnSubMeshes) {
  29774. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29775. var subMesh = _a[_i];
  29776. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29777. if (forceDisposeEffect && subMesh._materialEffect) {
  29778. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29779. }
  29780. }
  29781. }
  29782. else {
  29783. geometry._releaseVertexArrayObject(this._effect);
  29784. }
  29785. }
  29786. }
  29787. }
  29788. this._uniformBuffer.dispose();
  29789. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29790. if (forceDisposeEffect && this._effect) {
  29791. if (!this.storeEffectOnSubMeshes) {
  29792. this._scene.getEngine()._releaseEffect(this._effect);
  29793. }
  29794. this._effect = null;
  29795. }
  29796. // Callback
  29797. this.onDisposeObservable.notifyObservers(this);
  29798. this.onDisposeObservable.clear();
  29799. this.onBindObservable.clear();
  29800. this.onUnBindObservable.clear();
  29801. };
  29802. Material.prototype.serialize = function () {
  29803. return BABYLON.SerializationHelper.Serialize(this);
  29804. };
  29805. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29806. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29807. multiMaterial.id = parsedMultiMaterial.id;
  29808. if (BABYLON.Tags) {
  29809. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29810. }
  29811. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29812. var subMatId = parsedMultiMaterial.materials[matIndex];
  29813. if (subMatId) {
  29814. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29815. }
  29816. else {
  29817. multiMaterial.subMaterials.push(null);
  29818. }
  29819. }
  29820. return multiMaterial;
  29821. };
  29822. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29823. if (!parsedMaterial.customType) {
  29824. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29825. }
  29826. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29827. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29828. if (!BABYLON.LegacyPBRMaterial) {
  29829. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29830. return;
  29831. }
  29832. }
  29833. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29834. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29835. ;
  29836. };
  29837. // Triangle views
  29838. Material._TriangleFillMode = 0;
  29839. Material._WireFrameFillMode = 1;
  29840. Material._PointFillMode = 2;
  29841. // Draw modes
  29842. Material._PointListDrawMode = 3;
  29843. Material._LineListDrawMode = 4;
  29844. Material._LineLoopDrawMode = 5;
  29845. Material._LineStripDrawMode = 6;
  29846. Material._TriangleStripDrawMode = 7;
  29847. Material._TriangleFanDrawMode = 8;
  29848. Material._ClockWiseSideOrientation = 0;
  29849. Material._CounterClockWiseSideOrientation = 1;
  29850. Material._TextureDirtyFlag = 1;
  29851. Material._LightDirtyFlag = 2;
  29852. Material._FresnelDirtyFlag = 4;
  29853. Material._AttributesDirtyFlag = 8;
  29854. Material._MiscDirtyFlag = 16;
  29855. __decorate([
  29856. BABYLON.serialize()
  29857. ], Material.prototype, "id", void 0);
  29858. __decorate([
  29859. BABYLON.serialize()
  29860. ], Material.prototype, "name", void 0);
  29861. __decorate([
  29862. BABYLON.serialize()
  29863. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29864. __decorate([
  29865. BABYLON.serialize()
  29866. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29867. __decorate([
  29868. BABYLON.serialize()
  29869. ], Material.prototype, "state", void 0);
  29870. __decorate([
  29871. BABYLON.serialize("alpha")
  29872. ], Material.prototype, "_alpha", void 0);
  29873. __decorate([
  29874. BABYLON.serialize("backFaceCulling")
  29875. ], Material.prototype, "_backFaceCulling", void 0);
  29876. __decorate([
  29877. BABYLON.serialize()
  29878. ], Material.prototype, "sideOrientation", void 0);
  29879. __decorate([
  29880. BABYLON.serialize("alphaMode")
  29881. ], Material.prototype, "_alphaMode", void 0);
  29882. __decorate([
  29883. BABYLON.serialize()
  29884. ], Material.prototype, "_needDepthPrePass", void 0);
  29885. __decorate([
  29886. BABYLON.serialize()
  29887. ], Material.prototype, "disableDepthWrite", void 0);
  29888. __decorate([
  29889. BABYLON.serialize()
  29890. ], Material.prototype, "forceDepthWrite", void 0);
  29891. __decorate([
  29892. BABYLON.serialize()
  29893. ], Material.prototype, "separateCullingPass", void 0);
  29894. __decorate([
  29895. BABYLON.serialize("fogEnabled")
  29896. ], Material.prototype, "_fogEnabled", void 0);
  29897. __decorate([
  29898. BABYLON.serialize()
  29899. ], Material.prototype, "pointSize", void 0);
  29900. __decorate([
  29901. BABYLON.serialize()
  29902. ], Material.prototype, "zOffset", void 0);
  29903. __decorate([
  29904. BABYLON.serialize()
  29905. ], Material.prototype, "wireframe", null);
  29906. __decorate([
  29907. BABYLON.serialize()
  29908. ], Material.prototype, "pointsCloud", null);
  29909. __decorate([
  29910. BABYLON.serialize()
  29911. ], Material.prototype, "fillMode", null);
  29912. return Material;
  29913. }());
  29914. BABYLON.Material = Material;
  29915. })(BABYLON || (BABYLON = {}));
  29916. //# sourceMappingURL=babylon.material.js.map
  29917. var BABYLON;
  29918. (function (BABYLON) {
  29919. var UniformBuffer = /** @class */ (function () {
  29920. /**
  29921. * Uniform buffer objects.
  29922. *
  29923. * Handles blocks of uniform on the GPU.
  29924. *
  29925. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29926. *
  29927. * For more information, please refer to :
  29928. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29929. */
  29930. function UniformBuffer(engine, data, dynamic) {
  29931. this._engine = engine;
  29932. this._noUBO = !engine.supportsUniformBuffers;
  29933. this._dynamic = dynamic;
  29934. this._data = data || [];
  29935. this._uniformLocations = {};
  29936. this._uniformSizes = {};
  29937. this._uniformLocationPointer = 0;
  29938. this._needSync = false;
  29939. if (this._noUBO) {
  29940. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29941. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29942. this.updateFloat = this._updateFloatForEffect;
  29943. this.updateFloat2 = this._updateFloat2ForEffect;
  29944. this.updateFloat3 = this._updateFloat3ForEffect;
  29945. this.updateFloat4 = this._updateFloat4ForEffect;
  29946. this.updateMatrix = this._updateMatrixForEffect;
  29947. this.updateVector3 = this._updateVector3ForEffect;
  29948. this.updateVector4 = this._updateVector4ForEffect;
  29949. this.updateColor3 = this._updateColor3ForEffect;
  29950. this.updateColor4 = this._updateColor4ForEffect;
  29951. }
  29952. else {
  29953. this._engine._uniformBuffers.push(this);
  29954. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29955. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29956. this.updateFloat = this._updateFloatForUniform;
  29957. this.updateFloat2 = this._updateFloat2ForUniform;
  29958. this.updateFloat3 = this._updateFloat3ForUniform;
  29959. this.updateFloat4 = this._updateFloat4ForUniform;
  29960. this.updateMatrix = this._updateMatrixForUniform;
  29961. this.updateVector3 = this._updateVector3ForUniform;
  29962. this.updateVector4 = this._updateVector4ForUniform;
  29963. this.updateColor3 = this._updateColor3ForUniform;
  29964. this.updateColor4 = this._updateColor4ForUniform;
  29965. }
  29966. }
  29967. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29968. // Properties
  29969. /**
  29970. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29971. * or just falling back on setUniformXXX calls.
  29972. */
  29973. get: function () {
  29974. return !this._noUBO;
  29975. },
  29976. enumerable: true,
  29977. configurable: true
  29978. });
  29979. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29980. /**
  29981. * Indicates if the WebGL underlying uniform buffer is in sync
  29982. * with the javascript cache data.
  29983. */
  29984. get: function () {
  29985. return !this._needSync;
  29986. },
  29987. enumerable: true,
  29988. configurable: true
  29989. });
  29990. /**
  29991. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29992. * Also, a dynamic UniformBuffer will disable cache verification and always
  29993. * update the underlying WebGL uniform buffer to the GPU.
  29994. */
  29995. UniformBuffer.prototype.isDynamic = function () {
  29996. return this._dynamic !== undefined;
  29997. };
  29998. /**
  29999. * The data cache on JS side.
  30000. */
  30001. UniformBuffer.prototype.getData = function () {
  30002. return this._bufferData;
  30003. };
  30004. /**
  30005. * The underlying WebGL Uniform buffer.
  30006. */
  30007. UniformBuffer.prototype.getBuffer = function () {
  30008. return this._buffer;
  30009. };
  30010. /**
  30011. * std140 layout specifies how to align data within an UBO structure.
  30012. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  30013. * for specs.
  30014. */
  30015. UniformBuffer.prototype._fillAlignment = function (size) {
  30016. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  30017. // and 4x4 matrices
  30018. // TODO : change if other types are used
  30019. var alignment;
  30020. if (size <= 2) {
  30021. alignment = size;
  30022. }
  30023. else {
  30024. alignment = 4;
  30025. }
  30026. if ((this._uniformLocationPointer % alignment) !== 0) {
  30027. var oldPointer = this._uniformLocationPointer;
  30028. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  30029. var diff = this._uniformLocationPointer - oldPointer;
  30030. for (var i = 0; i < diff; i++) {
  30031. this._data.push(0);
  30032. }
  30033. }
  30034. };
  30035. /**
  30036. * Adds an uniform in the buffer.
  30037. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  30038. * for the layout to be correct !
  30039. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30040. * @param {number|number[]} size Data size, or data directly.
  30041. */
  30042. UniformBuffer.prototype.addUniform = function (name, size) {
  30043. if (this._noUBO) {
  30044. return;
  30045. }
  30046. if (this._uniformLocations[name] !== undefined) {
  30047. // Already existing uniform
  30048. return;
  30049. }
  30050. // This function must be called in the order of the shader layout !
  30051. // size can be the size of the uniform, or data directly
  30052. var data;
  30053. if (size instanceof Array) {
  30054. data = size;
  30055. size = data.length;
  30056. }
  30057. else {
  30058. size = size;
  30059. data = [];
  30060. // Fill with zeros
  30061. for (var i = 0; i < size; i++) {
  30062. data.push(0);
  30063. }
  30064. }
  30065. this._fillAlignment(size);
  30066. this._uniformSizes[name] = size;
  30067. this._uniformLocations[name] = this._uniformLocationPointer;
  30068. this._uniformLocationPointer += size;
  30069. for (var i = 0; i < size; i++) {
  30070. this._data.push(data[i]);
  30071. }
  30072. this._needSync = true;
  30073. };
  30074. /**
  30075. * Wrapper for addUniform.
  30076. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30077. * @param {Matrix} mat A 4x4 matrix.
  30078. */
  30079. UniformBuffer.prototype.addMatrix = function (name, mat) {
  30080. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  30081. };
  30082. /**
  30083. * Wrapper for addUniform.
  30084. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30085. * @param {number} x
  30086. * @param {number} y
  30087. */
  30088. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  30089. var temp = [x, y];
  30090. this.addUniform(name, temp);
  30091. };
  30092. /**
  30093. * Wrapper for addUniform.
  30094. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30095. * @param {number} x
  30096. * @param {number} y
  30097. * @param {number} z
  30098. */
  30099. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  30100. var temp = [x, y, z];
  30101. this.addUniform(name, temp);
  30102. };
  30103. /**
  30104. * Wrapper for addUniform.
  30105. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30106. * @param {Color3} color
  30107. */
  30108. UniformBuffer.prototype.addColor3 = function (name, color) {
  30109. var temp = new Array();
  30110. color.toArray(temp);
  30111. this.addUniform(name, temp);
  30112. };
  30113. /**
  30114. * Wrapper for addUniform.
  30115. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30116. * @param {Color3} color
  30117. * @param {number} alpha
  30118. */
  30119. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  30120. var temp = new Array();
  30121. color.toArray(temp);
  30122. temp.push(alpha);
  30123. this.addUniform(name, temp);
  30124. };
  30125. /**
  30126. * Wrapper for addUniform.
  30127. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30128. * @param {Vector3} vector
  30129. */
  30130. UniformBuffer.prototype.addVector3 = function (name, vector) {
  30131. var temp = new Array();
  30132. vector.toArray(temp);
  30133. this.addUniform(name, temp);
  30134. };
  30135. /**
  30136. * Wrapper for addUniform.
  30137. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30138. */
  30139. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  30140. this.addUniform(name, 12);
  30141. };
  30142. /**
  30143. * Wrapper for addUniform.
  30144. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  30145. */
  30146. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  30147. this.addUniform(name, 8);
  30148. };
  30149. /**
  30150. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  30151. */
  30152. UniformBuffer.prototype.create = function () {
  30153. if (this._noUBO) {
  30154. return;
  30155. }
  30156. if (this._buffer) {
  30157. return; // nothing to do
  30158. }
  30159. // See spec, alignment must be filled as a vec4
  30160. this._fillAlignment(4);
  30161. this._bufferData = new Float32Array(this._data);
  30162. this._rebuild();
  30163. this._needSync = true;
  30164. };
  30165. UniformBuffer.prototype._rebuild = function () {
  30166. if (this._noUBO) {
  30167. return;
  30168. }
  30169. if (this._dynamic) {
  30170. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  30171. }
  30172. else {
  30173. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  30174. }
  30175. };
  30176. /**
  30177. * Updates the WebGL Uniform Buffer on the GPU.
  30178. * If the `dynamic` flag is set to true, no cache comparison is done.
  30179. * Otherwise, the buffer will be updated only if the cache differs.
  30180. */
  30181. UniformBuffer.prototype.update = function () {
  30182. if (!this._buffer) {
  30183. this.create();
  30184. return;
  30185. }
  30186. if (!this._dynamic && !this._needSync) {
  30187. return;
  30188. }
  30189. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  30190. this._needSync = false;
  30191. };
  30192. /**
  30193. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  30194. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30195. * @param {number[]|Float32Array} data Flattened data
  30196. * @param {number} size Size of the data.
  30197. */
  30198. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  30199. var location = this._uniformLocations[uniformName];
  30200. if (location === undefined) {
  30201. if (this._buffer) {
  30202. // Cannot add an uniform if the buffer is already created
  30203. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  30204. return;
  30205. }
  30206. this.addUniform(uniformName, size);
  30207. location = this._uniformLocations[uniformName];
  30208. }
  30209. if (!this._buffer) {
  30210. this.create();
  30211. }
  30212. if (!this._dynamic) {
  30213. // Cache for static uniform buffers
  30214. var changed = false;
  30215. for (var i = 0; i < size; i++) {
  30216. if (this._bufferData[location + i] !== data[i]) {
  30217. changed = true;
  30218. this._bufferData[location + i] = data[i];
  30219. }
  30220. }
  30221. this._needSync = this._needSync || changed;
  30222. }
  30223. else {
  30224. // No cache for dynamic
  30225. for (var i = 0; i < size; i++) {
  30226. this._bufferData[location + i] = data[i];
  30227. }
  30228. }
  30229. };
  30230. // Update methods
  30231. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  30232. // To match std140, matrix must be realigned
  30233. for (var i = 0; i < 3; i++) {
  30234. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  30235. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  30236. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  30237. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30238. }
  30239. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  30240. };
  30241. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  30242. this._currentEffect.setMatrix3x3(name, matrix);
  30243. };
  30244. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  30245. this._currentEffect.setMatrix2x2(name, matrix);
  30246. };
  30247. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  30248. // To match std140, matrix must be realigned
  30249. for (var i = 0; i < 2; i++) {
  30250. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  30251. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  30252. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  30253. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30254. }
  30255. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  30256. };
  30257. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  30258. this._currentEffect.setFloat(name, x);
  30259. };
  30260. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  30261. UniformBuffer._tempBuffer[0] = x;
  30262. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  30263. };
  30264. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  30265. if (suffix === void 0) { suffix = ""; }
  30266. this._currentEffect.setFloat2(name + suffix, x, y);
  30267. };
  30268. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  30269. if (suffix === void 0) { suffix = ""; }
  30270. UniformBuffer._tempBuffer[0] = x;
  30271. UniformBuffer._tempBuffer[1] = y;
  30272. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  30273. };
  30274. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  30275. if (suffix === void 0) { suffix = ""; }
  30276. this._currentEffect.setFloat3(name + suffix, x, y, z);
  30277. };
  30278. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  30279. if (suffix === void 0) { suffix = ""; }
  30280. UniformBuffer._tempBuffer[0] = x;
  30281. UniformBuffer._tempBuffer[1] = y;
  30282. UniformBuffer._tempBuffer[2] = z;
  30283. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30284. };
  30285. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  30286. if (suffix === void 0) { suffix = ""; }
  30287. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  30288. };
  30289. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  30290. if (suffix === void 0) { suffix = ""; }
  30291. UniformBuffer._tempBuffer[0] = x;
  30292. UniformBuffer._tempBuffer[1] = y;
  30293. UniformBuffer._tempBuffer[2] = z;
  30294. UniformBuffer._tempBuffer[3] = w;
  30295. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30296. };
  30297. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  30298. this._currentEffect.setMatrix(name, mat);
  30299. };
  30300. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  30301. this.updateUniform(name, mat.toArray(), 16);
  30302. };
  30303. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  30304. this._currentEffect.setVector3(name, vector);
  30305. };
  30306. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  30307. vector.toArray(UniformBuffer._tempBuffer);
  30308. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30309. };
  30310. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  30311. this._currentEffect.setVector4(name, vector);
  30312. };
  30313. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  30314. vector.toArray(UniformBuffer._tempBuffer);
  30315. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30316. };
  30317. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  30318. if (suffix === void 0) { suffix = ""; }
  30319. this._currentEffect.setColor3(name + suffix, color);
  30320. };
  30321. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  30322. if (suffix === void 0) { suffix = ""; }
  30323. color.toArray(UniformBuffer._tempBuffer);
  30324. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30325. };
  30326. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  30327. if (suffix === void 0) { suffix = ""; }
  30328. this._currentEffect.setColor4(name + suffix, color, alpha);
  30329. };
  30330. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  30331. if (suffix === void 0) { suffix = ""; }
  30332. color.toArray(UniformBuffer._tempBuffer);
  30333. UniformBuffer._tempBuffer[3] = alpha;
  30334. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30335. };
  30336. /**
  30337. * Sets a sampler uniform on the effect.
  30338. * @param {string} name Name of the sampler.
  30339. * @param {Texture} texture
  30340. */
  30341. UniformBuffer.prototype.setTexture = function (name, texture) {
  30342. this._currentEffect.setTexture(name, texture);
  30343. };
  30344. /**
  30345. * Directly updates the value of the uniform in the cache AND on the GPU.
  30346. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30347. * @param {number[]|Float32Array} data Flattened data
  30348. */
  30349. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  30350. this.updateUniform(uniformName, data, data.length);
  30351. this.update();
  30352. };
  30353. /**
  30354. * Binds this uniform buffer to an effect.
  30355. * @param {Effect} effect
  30356. * @param {string} name Name of the uniform block in the shader.
  30357. */
  30358. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  30359. this._currentEffect = effect;
  30360. if (this._noUBO || !this._buffer) {
  30361. return;
  30362. }
  30363. effect.bindUniformBuffer(this._buffer, name);
  30364. };
  30365. /**
  30366. * Disposes the uniform buffer.
  30367. */
  30368. UniformBuffer.prototype.dispose = function () {
  30369. if (this._noUBO) {
  30370. return;
  30371. }
  30372. var index = this._engine._uniformBuffers.indexOf(this);
  30373. if (index !== -1) {
  30374. this._engine._uniformBuffers.splice(index, 1);
  30375. }
  30376. if (!this._buffer) {
  30377. return;
  30378. }
  30379. if (this._engine._releaseBuffer(this._buffer)) {
  30380. this._buffer = null;
  30381. }
  30382. };
  30383. // Pool for avoiding memory leaks
  30384. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  30385. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30386. return UniformBuffer;
  30387. }());
  30388. BABYLON.UniformBuffer = UniformBuffer;
  30389. })(BABYLON || (BABYLON = {}));
  30390. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30391. var BABYLON;
  30392. (function (BABYLON) {
  30393. var VertexData = /** @class */ (function () {
  30394. function VertexData() {
  30395. }
  30396. VertexData.prototype.set = function (data, kind) {
  30397. switch (kind) {
  30398. case BABYLON.VertexBuffer.PositionKind:
  30399. this.positions = data;
  30400. break;
  30401. case BABYLON.VertexBuffer.NormalKind:
  30402. this.normals = data;
  30403. break;
  30404. case BABYLON.VertexBuffer.TangentKind:
  30405. this.tangents = data;
  30406. break;
  30407. case BABYLON.VertexBuffer.UVKind:
  30408. this.uvs = data;
  30409. break;
  30410. case BABYLON.VertexBuffer.UV2Kind:
  30411. this.uvs2 = data;
  30412. break;
  30413. case BABYLON.VertexBuffer.UV3Kind:
  30414. this.uvs3 = data;
  30415. break;
  30416. case BABYLON.VertexBuffer.UV4Kind:
  30417. this.uvs4 = data;
  30418. break;
  30419. case BABYLON.VertexBuffer.UV5Kind:
  30420. this.uvs5 = data;
  30421. break;
  30422. case BABYLON.VertexBuffer.UV6Kind:
  30423. this.uvs6 = data;
  30424. break;
  30425. case BABYLON.VertexBuffer.ColorKind:
  30426. this.colors = data;
  30427. break;
  30428. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30429. this.matricesIndices = data;
  30430. break;
  30431. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30432. this.matricesWeights = data;
  30433. break;
  30434. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30435. this.matricesIndicesExtra = data;
  30436. break;
  30437. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30438. this.matricesWeightsExtra = data;
  30439. break;
  30440. }
  30441. };
  30442. /**
  30443. * Associates the vertexData to the passed Mesh.
  30444. * Sets it as updatable or not (default `false`).
  30445. * Returns the VertexData.
  30446. */
  30447. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30448. this._applyTo(mesh, updatable);
  30449. return this;
  30450. };
  30451. /**
  30452. * Associates the vertexData to the passed Geometry.
  30453. * Sets it as updatable or not (default `false`).
  30454. * Returns the VertexData.
  30455. */
  30456. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30457. this._applyTo(geometry, updatable);
  30458. return this;
  30459. };
  30460. /**
  30461. * Updates the associated mesh.
  30462. * Returns the VertexData.
  30463. */
  30464. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30465. this._update(mesh);
  30466. return this;
  30467. };
  30468. /**
  30469. * Updates the associated geometry.
  30470. * Returns the VertexData.
  30471. */
  30472. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30473. this._update(geometry);
  30474. return this;
  30475. };
  30476. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30477. if (updatable === void 0) { updatable = false; }
  30478. if (this.positions) {
  30479. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30480. }
  30481. if (this.normals) {
  30482. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30483. }
  30484. if (this.tangents) {
  30485. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30486. }
  30487. if (this.uvs) {
  30488. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30489. }
  30490. if (this.uvs2) {
  30491. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30492. }
  30493. if (this.uvs3) {
  30494. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30495. }
  30496. if (this.uvs4) {
  30497. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30498. }
  30499. if (this.uvs5) {
  30500. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30501. }
  30502. if (this.uvs6) {
  30503. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30504. }
  30505. if (this.colors) {
  30506. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30507. }
  30508. if (this.matricesIndices) {
  30509. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30510. }
  30511. if (this.matricesWeights) {
  30512. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30513. }
  30514. if (this.matricesIndicesExtra) {
  30515. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30516. }
  30517. if (this.matricesWeightsExtra) {
  30518. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30519. }
  30520. if (this.indices) {
  30521. meshOrGeometry.setIndices(this.indices, null, updatable);
  30522. }
  30523. return this;
  30524. };
  30525. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30526. if (this.positions) {
  30527. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30528. }
  30529. if (this.normals) {
  30530. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30531. }
  30532. if (this.tangents) {
  30533. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30534. }
  30535. if (this.uvs) {
  30536. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30537. }
  30538. if (this.uvs2) {
  30539. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30540. }
  30541. if (this.uvs3) {
  30542. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30543. }
  30544. if (this.uvs4) {
  30545. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30546. }
  30547. if (this.uvs5) {
  30548. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30549. }
  30550. if (this.uvs6) {
  30551. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30552. }
  30553. if (this.colors) {
  30554. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30555. }
  30556. if (this.matricesIndices) {
  30557. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30558. }
  30559. if (this.matricesWeights) {
  30560. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30561. }
  30562. if (this.matricesIndicesExtra) {
  30563. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30564. }
  30565. if (this.matricesWeightsExtra) {
  30566. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30567. }
  30568. if (this.indices) {
  30569. meshOrGeometry.setIndices(this.indices, null);
  30570. }
  30571. return this;
  30572. };
  30573. /**
  30574. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30575. * Returns the VertexData.
  30576. */
  30577. VertexData.prototype.transform = function (matrix) {
  30578. var transformed = BABYLON.Vector3.Zero();
  30579. var index;
  30580. if (this.positions) {
  30581. var position = BABYLON.Vector3.Zero();
  30582. for (index = 0; index < this.positions.length; index += 3) {
  30583. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30584. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30585. this.positions[index] = transformed.x;
  30586. this.positions[index + 1] = transformed.y;
  30587. this.positions[index + 2] = transformed.z;
  30588. }
  30589. }
  30590. if (this.normals) {
  30591. var normal = BABYLON.Vector3.Zero();
  30592. for (index = 0; index < this.normals.length; index += 3) {
  30593. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30594. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30595. this.normals[index] = transformed.x;
  30596. this.normals[index + 1] = transformed.y;
  30597. this.normals[index + 2] = transformed.z;
  30598. }
  30599. }
  30600. if (this.tangents) {
  30601. var tangent = BABYLON.Vector4.Zero();
  30602. var tangentTransformed = BABYLON.Vector4.Zero();
  30603. for (index = 0; index < this.tangents.length; index += 4) {
  30604. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30605. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30606. this.tangents[index] = tangentTransformed.x;
  30607. this.tangents[index + 1] = tangentTransformed.y;
  30608. this.tangents[index + 2] = tangentTransformed.z;
  30609. this.tangents[index + 3] = tangentTransformed.w;
  30610. }
  30611. }
  30612. return this;
  30613. };
  30614. /**
  30615. * Merges the passed VertexData into the current one.
  30616. * Returns the modified VertexData.
  30617. */
  30618. VertexData.prototype.merge = function (other, options) {
  30619. options = options || {};
  30620. if (other.indices) {
  30621. if (!this.indices) {
  30622. this.indices = [];
  30623. }
  30624. var offset = this.positions ? this.positions.length / 3 : 0;
  30625. for (var index = 0; index < other.indices.length; index++) {
  30626. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30627. this.indices.push(other.indices[index] + offset);
  30628. }
  30629. }
  30630. this.positions = this._mergeElement(this.positions, other.positions);
  30631. if (!this.positions) {
  30632. return this;
  30633. }
  30634. var count = this.positions.length / 3;
  30635. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30636. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30637. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30638. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30639. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30640. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30641. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30642. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30643. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30644. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30645. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30646. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30647. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30648. return this;
  30649. };
  30650. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30651. if (length === void 0) { length = 0; }
  30652. if (defaultValue === void 0) { defaultValue = 0; }
  30653. if (!other && !source) {
  30654. return null;
  30655. }
  30656. if (!other) {
  30657. var padding = new Float32Array(source.length);
  30658. padding.fill(defaultValue);
  30659. return this._mergeElement(source, padding, length);
  30660. }
  30661. if (!source) {
  30662. if (length === 0 || length === other.length) {
  30663. return other;
  30664. }
  30665. var padding = new Float32Array(length - other.length);
  30666. padding.fill(defaultValue);
  30667. return this._mergeElement(padding, other, length);
  30668. }
  30669. var len = other.length + source.length;
  30670. var isSrcTypedArray = source instanceof Float32Array;
  30671. var isOthTypedArray = other instanceof Float32Array;
  30672. // use non-loop method when the source is Float32Array
  30673. if (isSrcTypedArray) {
  30674. var ret32 = new Float32Array(len);
  30675. ret32.set(source);
  30676. ret32.set(other, source.length);
  30677. return ret32;
  30678. // source is number[], when other is also use concat
  30679. }
  30680. else if (!isOthTypedArray) {
  30681. return source.concat(other);
  30682. // source is a number[], but other is a Float32Array, loop required
  30683. }
  30684. else {
  30685. var ret = source.slice(0); // copy source to a separate array
  30686. for (var i = 0, len = other.length; i < len; i++) {
  30687. ret.push(other[i]);
  30688. }
  30689. return ret;
  30690. }
  30691. };
  30692. /**
  30693. * Serializes the VertexData.
  30694. * Returns a serialized object.
  30695. */
  30696. VertexData.prototype.serialize = function () {
  30697. var serializationObject = this.serialize();
  30698. if (this.positions) {
  30699. serializationObject.positions = this.positions;
  30700. }
  30701. if (this.normals) {
  30702. serializationObject.normals = this.normals;
  30703. }
  30704. if (this.tangents) {
  30705. serializationObject.tangents = this.tangents;
  30706. }
  30707. if (this.uvs) {
  30708. serializationObject.uvs = this.uvs;
  30709. }
  30710. if (this.uvs2) {
  30711. serializationObject.uvs2 = this.uvs2;
  30712. }
  30713. if (this.uvs3) {
  30714. serializationObject.uvs3 = this.uvs3;
  30715. }
  30716. if (this.uvs4) {
  30717. serializationObject.uvs4 = this.uvs4;
  30718. }
  30719. if (this.uvs5) {
  30720. serializationObject.uvs5 = this.uvs5;
  30721. }
  30722. if (this.uvs6) {
  30723. serializationObject.uvs6 = this.uvs6;
  30724. }
  30725. if (this.colors) {
  30726. serializationObject.colors = this.colors;
  30727. }
  30728. if (this.matricesIndices) {
  30729. serializationObject.matricesIndices = this.matricesIndices;
  30730. serializationObject.matricesIndices._isExpanded = true;
  30731. }
  30732. if (this.matricesWeights) {
  30733. serializationObject.matricesWeights = this.matricesWeights;
  30734. }
  30735. if (this.matricesIndicesExtra) {
  30736. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30737. serializationObject.matricesIndicesExtra._isExpanded = true;
  30738. }
  30739. if (this.matricesWeightsExtra) {
  30740. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30741. }
  30742. serializationObject.indices = this.indices;
  30743. return serializationObject;
  30744. };
  30745. // Statics
  30746. /**
  30747. * Returns the object VertexData associated to the passed mesh.
  30748. */
  30749. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30750. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30751. };
  30752. /**
  30753. * Returns the object VertexData associated to the passed geometry.
  30754. */
  30755. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30756. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30757. };
  30758. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30759. var result = new VertexData();
  30760. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30761. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30762. }
  30763. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30764. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30765. }
  30766. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30767. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30768. }
  30769. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30770. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30771. }
  30772. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30773. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30774. }
  30775. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30776. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30777. }
  30778. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30779. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30780. }
  30781. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30782. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30783. }
  30784. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30785. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30786. }
  30787. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30788. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30789. }
  30790. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30791. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30792. }
  30793. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30794. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30795. }
  30796. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30797. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30798. }
  30799. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30800. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30801. }
  30802. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30803. return result;
  30804. };
  30805. /**
  30806. * Creates the vertexData of the Ribbon.
  30807. */
  30808. VertexData.CreateRibbon = function (options) {
  30809. var pathArray = options.pathArray;
  30810. var closeArray = options.closeArray || false;
  30811. var closePath = options.closePath || false;
  30812. var invertUV = options.invertUV || false;
  30813. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30814. var offset = options.offset || defaultOffset;
  30815. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30816. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30817. var customUV = options.uvs;
  30818. var customColors = options.colors;
  30819. var positions = [];
  30820. var indices = [];
  30821. var normals = [];
  30822. var uvs = [];
  30823. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30824. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30825. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30826. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30827. var minlg; // minimal length among all paths from pathArray
  30828. var lg = []; // array of path lengths : nb of vertex per path
  30829. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30830. var p; // path iterator
  30831. var i; // point iterator
  30832. var j; // point iterator
  30833. // if single path in pathArray
  30834. if (pathArray.length < 2) {
  30835. var ar1 = [];
  30836. var ar2 = [];
  30837. for (i = 0; i < pathArray[0].length - offset; i++) {
  30838. ar1.push(pathArray[0][i]);
  30839. ar2.push(pathArray[0][i + offset]);
  30840. }
  30841. pathArray = [ar1, ar2];
  30842. }
  30843. // positions and horizontal distances (u)
  30844. var idc = 0;
  30845. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30846. var path;
  30847. var l;
  30848. minlg = pathArray[0].length;
  30849. var vectlg;
  30850. var dist;
  30851. for (p = 0; p < pathArray.length; p++) {
  30852. uTotalDistance[p] = 0;
  30853. us[p] = [0];
  30854. path = pathArray[p];
  30855. l = path.length;
  30856. minlg = (minlg < l) ? minlg : l;
  30857. j = 0;
  30858. while (j < l) {
  30859. positions.push(path[j].x, path[j].y, path[j].z);
  30860. if (j > 0) {
  30861. vectlg = path[j].subtract(path[j - 1]).length();
  30862. dist = vectlg + uTotalDistance[p];
  30863. us[p].push(dist);
  30864. uTotalDistance[p] = dist;
  30865. }
  30866. j++;
  30867. }
  30868. if (closePath) {
  30869. j--;
  30870. positions.push(path[0].x, path[0].y, path[0].z);
  30871. vectlg = path[j].subtract(path[0]).length();
  30872. dist = vectlg + uTotalDistance[p];
  30873. us[p].push(dist);
  30874. uTotalDistance[p] = dist;
  30875. }
  30876. lg[p] = l + closePathCorr;
  30877. idx[p] = idc;
  30878. idc += (l + closePathCorr);
  30879. }
  30880. // vertical distances (v)
  30881. var path1;
  30882. var path2;
  30883. var vertex1 = null;
  30884. var vertex2 = null;
  30885. for (i = 0; i < minlg + closePathCorr; i++) {
  30886. vTotalDistance[i] = 0;
  30887. vs[i] = [0];
  30888. for (p = 0; p < pathArray.length - 1; p++) {
  30889. path1 = pathArray[p];
  30890. path2 = pathArray[p + 1];
  30891. if (i === minlg) {
  30892. vertex1 = path1[0];
  30893. vertex2 = path2[0];
  30894. }
  30895. else {
  30896. vertex1 = path1[i];
  30897. vertex2 = path2[i];
  30898. }
  30899. vectlg = vertex2.subtract(vertex1).length();
  30900. dist = vectlg + vTotalDistance[i];
  30901. vs[i].push(dist);
  30902. vTotalDistance[i] = dist;
  30903. }
  30904. if (closeArray && vertex2 && vertex1) {
  30905. path1 = pathArray[p];
  30906. path2 = pathArray[0];
  30907. if (i === minlg) {
  30908. vertex2 = path2[0];
  30909. }
  30910. vectlg = vertex2.subtract(vertex1).length();
  30911. dist = vectlg + vTotalDistance[i];
  30912. vTotalDistance[i] = dist;
  30913. }
  30914. }
  30915. // uvs
  30916. var u;
  30917. var v;
  30918. if (customUV) {
  30919. for (p = 0; p < customUV.length; p++) {
  30920. uvs.push(customUV[p].x, customUV[p].y);
  30921. }
  30922. }
  30923. else {
  30924. for (p = 0; p < pathArray.length; p++) {
  30925. for (i = 0; i < minlg + closePathCorr; i++) {
  30926. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30927. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30928. if (invertUV) {
  30929. uvs.push(v, u);
  30930. }
  30931. else {
  30932. uvs.push(u, v);
  30933. }
  30934. }
  30935. }
  30936. }
  30937. // indices
  30938. p = 0; // path index
  30939. var pi = 0; // positions array index
  30940. var l1 = lg[p] - 1; // path1 length
  30941. var l2 = lg[p + 1] - 1; // path2 length
  30942. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30943. var shft = idx[1] - idx[0]; // shift
  30944. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30945. while (pi <= min && p < path1nb) {
  30946. // 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
  30947. indices.push(pi, pi + shft, pi + 1);
  30948. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30949. pi += 1;
  30950. if (pi === min) {
  30951. p++;
  30952. if (p === lg.length - 1) {
  30953. shft = idx[0] - idx[p];
  30954. l1 = lg[p] - 1;
  30955. l2 = lg[0] - 1;
  30956. }
  30957. else {
  30958. shft = idx[p + 1] - idx[p];
  30959. l1 = lg[p] - 1;
  30960. l2 = lg[p + 1] - 1;
  30961. }
  30962. pi = idx[p];
  30963. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30964. }
  30965. }
  30966. // normals
  30967. VertexData.ComputeNormals(positions, indices, normals);
  30968. if (closePath) {
  30969. var indexFirst = 0;
  30970. var indexLast = 0;
  30971. for (p = 0; p < pathArray.length; p++) {
  30972. indexFirst = idx[p] * 3;
  30973. if (p + 1 < pathArray.length) {
  30974. indexLast = (idx[p + 1] - 1) * 3;
  30975. }
  30976. else {
  30977. indexLast = normals.length - 3;
  30978. }
  30979. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30980. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30981. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30982. normals[indexLast] = normals[indexFirst];
  30983. normals[indexLast + 1] = normals[indexFirst + 1];
  30984. normals[indexLast + 2] = normals[indexFirst + 2];
  30985. }
  30986. }
  30987. // sides
  30988. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30989. // Colors
  30990. var colors = null;
  30991. if (customColors) {
  30992. colors = new Float32Array(customColors.length * 4);
  30993. for (var c = 0; c < customColors.length; c++) {
  30994. colors[c * 4] = customColors[c].r;
  30995. colors[c * 4 + 1] = customColors[c].g;
  30996. colors[c * 4 + 2] = customColors[c].b;
  30997. colors[c * 4 + 3] = customColors[c].a;
  30998. }
  30999. }
  31000. // Result
  31001. var vertexData = new VertexData();
  31002. var positions32 = new Float32Array(positions);
  31003. var normals32 = new Float32Array(normals);
  31004. var uvs32 = new Float32Array(uvs);
  31005. vertexData.indices = indices;
  31006. vertexData.positions = positions32;
  31007. vertexData.normals = normals32;
  31008. vertexData.uvs = uvs32;
  31009. if (colors) {
  31010. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  31011. }
  31012. if (closePath) {
  31013. vertexData._idx = idx;
  31014. }
  31015. return vertexData;
  31016. };
  31017. /**
  31018. * Creates the VertexData of the Box.
  31019. */
  31020. VertexData.CreateBox = function (options) {
  31021. var normalsSource = [
  31022. new BABYLON.Vector3(0, 0, 1),
  31023. new BABYLON.Vector3(0, 0, -1),
  31024. new BABYLON.Vector3(1, 0, 0),
  31025. new BABYLON.Vector3(-1, 0, 0),
  31026. new BABYLON.Vector3(0, 1, 0),
  31027. new BABYLON.Vector3(0, -1, 0)
  31028. ];
  31029. var indices = [];
  31030. var positions = [];
  31031. var normals = [];
  31032. var uvs = [];
  31033. var width = options.width || options.size || 1;
  31034. var height = options.height || options.size || 1;
  31035. var depth = options.depth || options.size || 1;
  31036. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31037. var faceUV = options.faceUV || new Array(6);
  31038. var faceColors = options.faceColors;
  31039. var colors = [];
  31040. // default face colors and UV if undefined
  31041. for (var f = 0; f < 6; f++) {
  31042. if (faceUV[f] === undefined) {
  31043. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31044. }
  31045. if (faceColors && faceColors[f] === undefined) {
  31046. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31047. }
  31048. }
  31049. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31050. // Create each face in turn.
  31051. for (var index = 0; index < normalsSource.length; index++) {
  31052. var normal = normalsSource[index];
  31053. // Get two vectors perpendicular to the face normal and to each other.
  31054. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31055. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31056. // Six indices (two triangles) per face.
  31057. var verticesLength = positions.length / 3;
  31058. indices.push(verticesLength);
  31059. indices.push(verticesLength + 1);
  31060. indices.push(verticesLength + 2);
  31061. indices.push(verticesLength);
  31062. indices.push(verticesLength + 2);
  31063. indices.push(verticesLength + 3);
  31064. // Four vertices per face.
  31065. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31066. positions.push(vertex.x, vertex.y, vertex.z);
  31067. normals.push(normal.x, normal.y, normal.z);
  31068. uvs.push(faceUV[index].z, faceUV[index].w);
  31069. if (faceColors) {
  31070. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31071. }
  31072. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31073. positions.push(vertex.x, vertex.y, vertex.z);
  31074. normals.push(normal.x, normal.y, normal.z);
  31075. uvs.push(faceUV[index].x, faceUV[index].w);
  31076. if (faceColors) {
  31077. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31078. }
  31079. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31080. positions.push(vertex.x, vertex.y, vertex.z);
  31081. normals.push(normal.x, normal.y, normal.z);
  31082. uvs.push(faceUV[index].x, faceUV[index].y);
  31083. if (faceColors) {
  31084. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31085. }
  31086. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31087. positions.push(vertex.x, vertex.y, vertex.z);
  31088. normals.push(normal.x, normal.y, normal.z);
  31089. uvs.push(faceUV[index].z, faceUV[index].y);
  31090. if (faceColors) {
  31091. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31092. }
  31093. }
  31094. // sides
  31095. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31096. // Result
  31097. var vertexData = new VertexData();
  31098. vertexData.indices = indices;
  31099. vertexData.positions = positions;
  31100. vertexData.normals = normals;
  31101. vertexData.uvs = uvs;
  31102. if (faceColors) {
  31103. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31104. vertexData.colors = totalColors;
  31105. }
  31106. return vertexData;
  31107. };
  31108. /**
  31109. * Creates the VertexData of the Sphere.
  31110. */
  31111. VertexData.CreateSphere = function (options) {
  31112. var segments = options.segments || 32;
  31113. var diameterX = options.diameterX || options.diameter || 1;
  31114. var diameterY = options.diameterY || options.diameter || 1;
  31115. var diameterZ = options.diameterZ || options.diameter || 1;
  31116. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31117. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31118. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31119. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31120. var totalZRotationSteps = 2 + segments;
  31121. var totalYRotationSteps = 2 * totalZRotationSteps;
  31122. var indices = [];
  31123. var positions = [];
  31124. var normals = [];
  31125. var uvs = [];
  31126. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31127. var normalizedZ = zRotationStep / totalZRotationSteps;
  31128. var angleZ = normalizedZ * Math.PI * slice;
  31129. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31130. var normalizedY = yRotationStep / totalYRotationSteps;
  31131. var angleY = normalizedY * Math.PI * 2 * arc;
  31132. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31133. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31134. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31135. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31136. var vertex = complete.multiply(radius);
  31137. var normal = complete.divide(radius).normalize();
  31138. positions.push(vertex.x, vertex.y, vertex.z);
  31139. normals.push(normal.x, normal.y, normal.z);
  31140. uvs.push(normalizedY, normalizedZ);
  31141. }
  31142. if (zRotationStep > 0) {
  31143. var verticesCount = positions.length / 3;
  31144. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31145. indices.push((firstIndex));
  31146. indices.push((firstIndex + 1));
  31147. indices.push(firstIndex + totalYRotationSteps + 1);
  31148. indices.push((firstIndex + totalYRotationSteps + 1));
  31149. indices.push((firstIndex + 1));
  31150. indices.push((firstIndex + totalYRotationSteps + 2));
  31151. }
  31152. }
  31153. }
  31154. // Sides
  31155. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31156. // Result
  31157. var vertexData = new VertexData();
  31158. vertexData.indices = indices;
  31159. vertexData.positions = positions;
  31160. vertexData.normals = normals;
  31161. vertexData.uvs = uvs;
  31162. return vertexData;
  31163. };
  31164. /**
  31165. * Creates the VertexData of the Cylinder or Cone.
  31166. */
  31167. VertexData.CreateCylinder = function (options) {
  31168. var height = options.height || 2;
  31169. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31170. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31171. var tessellation = options.tessellation || 24;
  31172. var subdivisions = options.subdivisions || 1;
  31173. var hasRings = options.hasRings ? true : false;
  31174. var enclose = options.enclose ? true : false;
  31175. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31176. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31177. var faceUV = options.faceUV || new Array(3);
  31178. var faceColors = options.faceColors;
  31179. // default face colors and UV if undefined
  31180. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31181. var ringNb = (hasRings) ? subdivisions : 1;
  31182. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31183. var f;
  31184. for (f = 0; f < surfaceNb; f++) {
  31185. if (faceColors && faceColors[f] === undefined) {
  31186. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31187. }
  31188. }
  31189. for (f = 0; f < surfaceNb; f++) {
  31190. if (faceUV && faceUV[f] === undefined) {
  31191. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31192. }
  31193. }
  31194. var indices = new Array();
  31195. var positions = new Array();
  31196. var normals = new Array();
  31197. var uvs = new Array();
  31198. var colors = new Array();
  31199. var angle_step = Math.PI * 2 * arc / tessellation;
  31200. var angle;
  31201. var h;
  31202. var radius;
  31203. var tan = (diameterBottom - diameterTop) / 2 / height;
  31204. var ringVertex = BABYLON.Vector3.Zero();
  31205. var ringNormal = BABYLON.Vector3.Zero();
  31206. var ringFirstVertex = BABYLON.Vector3.Zero();
  31207. var ringFirstNormal = BABYLON.Vector3.Zero();
  31208. var quadNormal = BABYLON.Vector3.Zero();
  31209. var Y = BABYLON.Axis.Y;
  31210. // positions, normals, uvs
  31211. var i;
  31212. var j;
  31213. var r;
  31214. var ringIdx = 1;
  31215. var s = 1; // surface index
  31216. var cs = 0;
  31217. var v = 0;
  31218. for (i = 0; i <= subdivisions; i++) {
  31219. h = i / subdivisions;
  31220. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31221. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31222. for (r = 0; r < ringIdx; r++) {
  31223. if (hasRings) {
  31224. s += r;
  31225. }
  31226. if (enclose) {
  31227. s += 2 * r;
  31228. }
  31229. for (j = 0; j <= tessellation; j++) {
  31230. angle = j * angle_step;
  31231. // position
  31232. ringVertex.x = Math.cos(-angle) * radius;
  31233. ringVertex.y = -height / 2 + h * height;
  31234. ringVertex.z = Math.sin(-angle) * radius;
  31235. // normal
  31236. if (diameterTop === 0 && i === subdivisions) {
  31237. // if no top cap, reuse former normals
  31238. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31239. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31240. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31241. }
  31242. else {
  31243. ringNormal.x = ringVertex.x;
  31244. ringNormal.z = ringVertex.z;
  31245. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31246. ringNormal.normalize();
  31247. }
  31248. // keep first ring vertex values for enclose
  31249. if (j === 0) {
  31250. ringFirstVertex.copyFrom(ringVertex);
  31251. ringFirstNormal.copyFrom(ringNormal);
  31252. }
  31253. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31254. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31255. if (hasRings) {
  31256. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31257. }
  31258. else {
  31259. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31260. }
  31261. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31262. if (faceColors) {
  31263. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31264. }
  31265. }
  31266. // if enclose, add four vertices and their dedicated normals
  31267. if (arc !== 1 && enclose) {
  31268. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31269. positions.push(0, ringVertex.y, 0);
  31270. positions.push(0, ringVertex.y, 0);
  31271. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31272. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31273. quadNormal.normalize();
  31274. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31275. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31276. quadNormal.normalize();
  31277. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31278. if (hasRings) {
  31279. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31280. }
  31281. else {
  31282. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31283. }
  31284. uvs.push(faceUV[s + 1].x, v);
  31285. uvs.push(faceUV[s + 1].z, v);
  31286. if (hasRings) {
  31287. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31288. }
  31289. else {
  31290. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31291. }
  31292. uvs.push(faceUV[s + 2].x, v);
  31293. uvs.push(faceUV[s + 2].z, v);
  31294. if (faceColors) {
  31295. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31296. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31297. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31298. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31299. }
  31300. }
  31301. if (cs !== s) {
  31302. cs = s;
  31303. }
  31304. }
  31305. }
  31306. // indices
  31307. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31308. var s;
  31309. i = 0;
  31310. for (s = 0; s < subdivisions; s++) {
  31311. var i0 = 0;
  31312. var i1 = 0;
  31313. var i2 = 0;
  31314. var i3 = 0;
  31315. for (j = 0; j < tessellation; j++) {
  31316. i0 = i * (e + 1) + j;
  31317. i1 = (i + 1) * (e + 1) + j;
  31318. i2 = i * (e + 1) + (j + 1);
  31319. i3 = (i + 1) * (e + 1) + (j + 1);
  31320. indices.push(i0, i1, i2);
  31321. indices.push(i3, i2, i1);
  31322. }
  31323. if (arc !== 1 && enclose) {
  31324. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31325. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31326. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31327. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31328. }
  31329. i = (hasRings) ? (i + 2) : (i + 1);
  31330. }
  31331. // Caps
  31332. var createCylinderCap = function (isTop) {
  31333. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31334. if (radius === 0) {
  31335. return;
  31336. }
  31337. // Cap positions, normals & uvs
  31338. var angle;
  31339. var circleVector;
  31340. var i;
  31341. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31342. var c = null;
  31343. if (faceColors) {
  31344. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31345. }
  31346. // cap center
  31347. var vbase = positions.length / 3;
  31348. var offset = isTop ? height / 2 : -height / 2;
  31349. var center = new BABYLON.Vector3(0, offset, 0);
  31350. positions.push(center.x, center.y, center.z);
  31351. normals.push(0, isTop ? 1 : -1, 0);
  31352. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31353. if (c) {
  31354. colors.push(c.r, c.g, c.b, c.a);
  31355. }
  31356. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31357. for (i = 0; i <= tessellation; i++) {
  31358. angle = Math.PI * 2 * i * arc / tessellation;
  31359. var cos = Math.cos(-angle);
  31360. var sin = Math.sin(-angle);
  31361. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31362. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31363. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31364. normals.push(0, isTop ? 1 : -1, 0);
  31365. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31366. if (c) {
  31367. colors.push(c.r, c.g, c.b, c.a);
  31368. }
  31369. }
  31370. // Cap indices
  31371. for (i = 0; i < tessellation; i++) {
  31372. if (!isTop) {
  31373. indices.push(vbase);
  31374. indices.push(vbase + (i + 1));
  31375. indices.push(vbase + (i + 2));
  31376. }
  31377. else {
  31378. indices.push(vbase);
  31379. indices.push(vbase + (i + 2));
  31380. indices.push(vbase + (i + 1));
  31381. }
  31382. }
  31383. };
  31384. // add caps to geometry
  31385. createCylinderCap(false);
  31386. createCylinderCap(true);
  31387. // Sides
  31388. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31389. var vertexData = new VertexData();
  31390. vertexData.indices = indices;
  31391. vertexData.positions = positions;
  31392. vertexData.normals = normals;
  31393. vertexData.uvs = uvs;
  31394. if (faceColors) {
  31395. vertexData.colors = colors;
  31396. }
  31397. return vertexData;
  31398. };
  31399. /**
  31400. * Creates the VertexData of the Torus.
  31401. */
  31402. VertexData.CreateTorus = function (options) {
  31403. var indices = [];
  31404. var positions = [];
  31405. var normals = [];
  31406. var uvs = [];
  31407. var diameter = options.diameter || 1;
  31408. var thickness = options.thickness || 0.5;
  31409. var tessellation = options.tessellation || 16;
  31410. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31411. var stride = tessellation + 1;
  31412. for (var i = 0; i <= tessellation; i++) {
  31413. var u = i / tessellation;
  31414. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31415. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31416. for (var j = 0; j <= tessellation; j++) {
  31417. var v = 1 - j / tessellation;
  31418. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31419. var dx = Math.cos(innerAngle);
  31420. var dy = Math.sin(innerAngle);
  31421. // Create a vertex.
  31422. var normal = new BABYLON.Vector3(dx, dy, 0);
  31423. var position = normal.scale(thickness / 2);
  31424. var textureCoordinate = new BABYLON.Vector2(u, v);
  31425. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31426. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31427. positions.push(position.x, position.y, position.z);
  31428. normals.push(normal.x, normal.y, normal.z);
  31429. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31430. // And create indices for two triangles.
  31431. var nextI = (i + 1) % stride;
  31432. var nextJ = (j + 1) % stride;
  31433. indices.push(i * stride + j);
  31434. indices.push(i * stride + nextJ);
  31435. indices.push(nextI * stride + j);
  31436. indices.push(i * stride + nextJ);
  31437. indices.push(nextI * stride + nextJ);
  31438. indices.push(nextI * stride + j);
  31439. }
  31440. }
  31441. // Sides
  31442. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31443. // Result
  31444. var vertexData = new VertexData();
  31445. vertexData.indices = indices;
  31446. vertexData.positions = positions;
  31447. vertexData.normals = normals;
  31448. vertexData.uvs = uvs;
  31449. return vertexData;
  31450. };
  31451. /**
  31452. * Creates the VertexData of the LineSystem.
  31453. */
  31454. VertexData.CreateLineSystem = function (options) {
  31455. var indices = [];
  31456. var positions = [];
  31457. var lines = options.lines;
  31458. var colors = options.colors;
  31459. var vertexColors = [];
  31460. var idx = 0;
  31461. for (var l = 0; l < lines.length; l++) {
  31462. var points = lines[l];
  31463. for (var index = 0; index < points.length; index++) {
  31464. positions.push(points[index].x, points[index].y, points[index].z);
  31465. if (colors) {
  31466. var color = colors[l];
  31467. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31468. }
  31469. if (index > 0) {
  31470. indices.push(idx - 1);
  31471. indices.push(idx);
  31472. }
  31473. idx++;
  31474. }
  31475. }
  31476. var vertexData = new VertexData();
  31477. vertexData.indices = indices;
  31478. vertexData.positions = positions;
  31479. if (colors) {
  31480. vertexData.colors = vertexColors;
  31481. }
  31482. return vertexData;
  31483. };
  31484. /**
  31485. * Create the VertexData of the DashedLines.
  31486. */
  31487. VertexData.CreateDashedLines = function (options) {
  31488. var dashSize = options.dashSize || 3;
  31489. var gapSize = options.gapSize || 1;
  31490. var dashNb = options.dashNb || 200;
  31491. var points = options.points;
  31492. var positions = new Array();
  31493. var indices = new Array();
  31494. var curvect = BABYLON.Vector3.Zero();
  31495. var lg = 0;
  31496. var nb = 0;
  31497. var shft = 0;
  31498. var dashshft = 0;
  31499. var curshft = 0;
  31500. var idx = 0;
  31501. var i = 0;
  31502. for (i = 0; i < points.length - 1; i++) {
  31503. points[i + 1].subtractToRef(points[i], curvect);
  31504. lg += curvect.length();
  31505. }
  31506. shft = lg / dashNb;
  31507. dashshft = dashSize * shft / (dashSize + gapSize);
  31508. for (i = 0; i < points.length - 1; i++) {
  31509. points[i + 1].subtractToRef(points[i], curvect);
  31510. nb = Math.floor(curvect.length() / shft);
  31511. curvect.normalize();
  31512. for (var j = 0; j < nb; j++) {
  31513. curshft = shft * j;
  31514. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31515. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31516. indices.push(idx, idx + 1);
  31517. idx += 2;
  31518. }
  31519. }
  31520. // Result
  31521. var vertexData = new VertexData();
  31522. vertexData.positions = positions;
  31523. vertexData.indices = indices;
  31524. return vertexData;
  31525. };
  31526. /**
  31527. * Creates the VertexData of the Ground.
  31528. */
  31529. VertexData.CreateGround = function (options) {
  31530. var indices = [];
  31531. var positions = [];
  31532. var normals = [];
  31533. var uvs = [];
  31534. var row, col;
  31535. var width = options.width || 1;
  31536. var height = options.height || 1;
  31537. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31538. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31539. for (row = 0; row <= subdivisionsY; row++) {
  31540. for (col = 0; col <= subdivisionsX; col++) {
  31541. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31542. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31543. positions.push(position.x, position.y, position.z);
  31544. normals.push(normal.x, normal.y, normal.z);
  31545. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31546. }
  31547. }
  31548. for (row = 0; row < subdivisionsY; row++) {
  31549. for (col = 0; col < subdivisionsX; col++) {
  31550. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31551. indices.push(col + 1 + row * (subdivisionsX + 1));
  31552. indices.push(col + row * (subdivisionsX + 1));
  31553. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31554. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31555. indices.push(col + row * (subdivisionsX + 1));
  31556. }
  31557. }
  31558. // Result
  31559. var vertexData = new VertexData();
  31560. vertexData.indices = indices;
  31561. vertexData.positions = positions;
  31562. vertexData.normals = normals;
  31563. vertexData.uvs = uvs;
  31564. return vertexData;
  31565. };
  31566. /**
  31567. * Creates the VertexData of the TiledGround.
  31568. */
  31569. VertexData.CreateTiledGround = function (options) {
  31570. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31571. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31572. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31573. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31574. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31575. var precision = options.precision || { w: 1, h: 1 };
  31576. var indices = new Array();
  31577. var positions = new Array();
  31578. var normals = new Array();
  31579. var uvs = new Array();
  31580. var row, col, tileRow, tileCol;
  31581. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31582. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31583. precision.w = (precision.w < 1) ? 1 : precision.w;
  31584. precision.h = (precision.h < 1) ? 1 : precision.h;
  31585. var tileSize = {
  31586. 'w': (xmax - xmin) / subdivisions.w,
  31587. 'h': (zmax - zmin) / subdivisions.h
  31588. };
  31589. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31590. // Indices
  31591. var base = positions.length / 3;
  31592. var rowLength = precision.w + 1;
  31593. for (row = 0; row < precision.h; row++) {
  31594. for (col = 0; col < precision.w; col++) {
  31595. var square = [
  31596. base + col + row * rowLength,
  31597. base + (col + 1) + row * rowLength,
  31598. base + (col + 1) + (row + 1) * rowLength,
  31599. base + col + (row + 1) * rowLength
  31600. ];
  31601. indices.push(square[1]);
  31602. indices.push(square[2]);
  31603. indices.push(square[3]);
  31604. indices.push(square[0]);
  31605. indices.push(square[1]);
  31606. indices.push(square[3]);
  31607. }
  31608. }
  31609. // Position, normals and uvs
  31610. var position = BABYLON.Vector3.Zero();
  31611. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31612. for (row = 0; row <= precision.h; row++) {
  31613. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31614. for (col = 0; col <= precision.w; col++) {
  31615. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31616. position.y = 0;
  31617. positions.push(position.x, position.y, position.z);
  31618. normals.push(normal.x, normal.y, normal.z);
  31619. uvs.push(col / precision.w, row / precision.h);
  31620. }
  31621. }
  31622. }
  31623. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31624. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31625. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31626. }
  31627. }
  31628. // Result
  31629. var vertexData = new VertexData();
  31630. vertexData.indices = indices;
  31631. vertexData.positions = positions;
  31632. vertexData.normals = normals;
  31633. vertexData.uvs = uvs;
  31634. return vertexData;
  31635. };
  31636. /**
  31637. * Creates the VertexData of the Ground designed from a heightmap.
  31638. */
  31639. VertexData.CreateGroundFromHeightMap = function (options) {
  31640. var indices = [];
  31641. var positions = [];
  31642. var normals = [];
  31643. var uvs = [];
  31644. var row, col;
  31645. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31646. // Vertices
  31647. for (row = 0; row <= options.subdivisions; row++) {
  31648. for (col = 0; col <= options.subdivisions; col++) {
  31649. 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));
  31650. // Compute height
  31651. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31652. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31653. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31654. var r = options.buffer[pos] / 255.0;
  31655. var g = options.buffer[pos + 1] / 255.0;
  31656. var b = options.buffer[pos + 2] / 255.0;
  31657. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31658. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31659. // Add vertex
  31660. positions.push(position.x, position.y, position.z);
  31661. normals.push(0, 0, 0);
  31662. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31663. }
  31664. }
  31665. // Indices
  31666. for (row = 0; row < options.subdivisions; row++) {
  31667. for (col = 0; col < options.subdivisions; col++) {
  31668. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31669. indices.push(col + 1 + row * (options.subdivisions + 1));
  31670. indices.push(col + row * (options.subdivisions + 1));
  31671. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31672. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31673. indices.push(col + row * (options.subdivisions + 1));
  31674. }
  31675. }
  31676. // Normals
  31677. VertexData.ComputeNormals(positions, indices, normals);
  31678. // Result
  31679. var vertexData = new VertexData();
  31680. vertexData.indices = indices;
  31681. vertexData.positions = positions;
  31682. vertexData.normals = normals;
  31683. vertexData.uvs = uvs;
  31684. return vertexData;
  31685. };
  31686. /**
  31687. * Creates the VertexData of the Plane.
  31688. */
  31689. VertexData.CreatePlane = function (options) {
  31690. var indices = [];
  31691. var positions = [];
  31692. var normals = [];
  31693. var uvs = [];
  31694. var width = options.width || options.size || 1;
  31695. var height = options.height || options.size || 1;
  31696. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31697. // Vertices
  31698. var halfWidth = width / 2.0;
  31699. var halfHeight = height / 2.0;
  31700. positions.push(-halfWidth, -halfHeight, 0);
  31701. normals.push(0, 0, -1.0);
  31702. uvs.push(0.0, 0.0);
  31703. positions.push(halfWidth, -halfHeight, 0);
  31704. normals.push(0, 0, -1.0);
  31705. uvs.push(1.0, 0.0);
  31706. positions.push(halfWidth, halfHeight, 0);
  31707. normals.push(0, 0, -1.0);
  31708. uvs.push(1.0, 1.0);
  31709. positions.push(-halfWidth, halfHeight, 0);
  31710. normals.push(0, 0, -1.0);
  31711. uvs.push(0.0, 1.0);
  31712. // Indices
  31713. indices.push(0);
  31714. indices.push(1);
  31715. indices.push(2);
  31716. indices.push(0);
  31717. indices.push(2);
  31718. indices.push(3);
  31719. // Sides
  31720. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31721. // Result
  31722. var vertexData = new VertexData();
  31723. vertexData.indices = indices;
  31724. vertexData.positions = positions;
  31725. vertexData.normals = normals;
  31726. vertexData.uvs = uvs;
  31727. return vertexData;
  31728. };
  31729. /**
  31730. * Creates the VertexData of the Disc or regular Polygon.
  31731. */
  31732. VertexData.CreateDisc = function (options) {
  31733. var positions = new Array();
  31734. var indices = new Array();
  31735. var normals = new Array();
  31736. var uvs = new Array();
  31737. var radius = options.radius || 0.5;
  31738. var tessellation = options.tessellation || 64;
  31739. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31740. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31741. // positions and uvs
  31742. positions.push(0, 0, 0); // disc center first
  31743. uvs.push(0.5, 0.5);
  31744. var theta = Math.PI * 2 * arc;
  31745. var step = theta / tessellation;
  31746. for (var a = 0; a < theta; a += step) {
  31747. var x = Math.cos(a);
  31748. var y = Math.sin(a);
  31749. var u = (x + 1) / 2;
  31750. var v = (1 - y) / 2;
  31751. positions.push(radius * x, radius * y, 0);
  31752. uvs.push(u, v);
  31753. }
  31754. if (arc === 1) {
  31755. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31756. uvs.push(uvs[2], uvs[3]);
  31757. }
  31758. //indices
  31759. var vertexNb = positions.length / 3;
  31760. for (var i = 1; i < vertexNb - 1; i++) {
  31761. indices.push(i + 1, 0, i);
  31762. }
  31763. // result
  31764. VertexData.ComputeNormals(positions, indices, normals);
  31765. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31766. var vertexData = new VertexData();
  31767. vertexData.indices = indices;
  31768. vertexData.positions = positions;
  31769. vertexData.normals = normals;
  31770. vertexData.uvs = uvs;
  31771. return vertexData;
  31772. };
  31773. /**
  31774. * Re-creates the VertexData of the Polygon for sideOrientation.
  31775. */
  31776. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31777. var faceUV = fUV || new Array(3);
  31778. var faceColors = fColors;
  31779. var colors = [];
  31780. // default face colors and UV if undefined
  31781. for (var f = 0; f < 3; f++) {
  31782. if (faceUV[f] === undefined) {
  31783. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31784. }
  31785. if (faceColors && faceColors[f] === undefined) {
  31786. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31787. }
  31788. }
  31789. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31790. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31791. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31792. var indices = polygon.getIndices();
  31793. // set face colours and textures
  31794. var idx = 0;
  31795. var face = 0;
  31796. for (var index = 0; index < normals.length; index += 3) {
  31797. //Edge Face no. 1
  31798. if (Math.abs(normals[index + 1]) < 0.001) {
  31799. face = 1;
  31800. }
  31801. //Top Face no. 0
  31802. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31803. face = 0;
  31804. }
  31805. //Bottom Face no. 2
  31806. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31807. face = 2;
  31808. }
  31809. idx = index / 3;
  31810. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31811. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31812. if (faceColors) {
  31813. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31814. }
  31815. }
  31816. // sides
  31817. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31818. // Result
  31819. var vertexData = new VertexData();
  31820. vertexData.indices = indices;
  31821. vertexData.positions = positions;
  31822. vertexData.normals = normals;
  31823. vertexData.uvs = uvs;
  31824. if (faceColors) {
  31825. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31826. vertexData.colors = totalColors;
  31827. }
  31828. return vertexData;
  31829. };
  31830. /**
  31831. * Creates the VertexData of the IcoSphere.
  31832. */
  31833. VertexData.CreateIcoSphere = function (options) {
  31834. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31835. var radius = options.radius || 1;
  31836. var flat = (options.flat === undefined) ? true : options.flat;
  31837. var subdivisions = options.subdivisions || 4;
  31838. var radiusX = options.radiusX || radius;
  31839. var radiusY = options.radiusY || radius;
  31840. var radiusZ = options.radiusZ || radius;
  31841. var t = (1 + Math.sqrt(5)) / 2;
  31842. // 12 vertex x,y,z
  31843. var ico_vertices = [
  31844. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31845. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31846. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31847. ];
  31848. // index of 3 vertex makes a face of icopshere
  31849. var ico_indices = [
  31850. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31851. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31852. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31853. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31854. ];
  31855. // vertex for uv have aliased position, not for UV
  31856. var vertices_unalias_id = [
  31857. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31858. // vertex alias
  31859. 0,
  31860. 2,
  31861. 3,
  31862. 3,
  31863. 3,
  31864. 4,
  31865. 7,
  31866. 8,
  31867. 9,
  31868. 9,
  31869. 10,
  31870. 11 // 23: B + 12
  31871. ];
  31872. // uv as integer step (not pixels !)
  31873. var ico_vertexuv = [
  31874. 5, 1, 3, 1, 6, 4, 0, 0,
  31875. 5, 3, 4, 2, 2, 2, 4, 0,
  31876. 2, 0, 1, 1, 6, 0, 6, 2,
  31877. // vertex alias (for same vertex on different faces)
  31878. 0, 4,
  31879. 3, 3,
  31880. 4, 4,
  31881. 3, 1,
  31882. 4, 2,
  31883. 4, 4,
  31884. 0, 2,
  31885. 1, 1,
  31886. 2, 2,
  31887. 3, 3,
  31888. 1, 3,
  31889. 2, 4 // 23: B + 12
  31890. ];
  31891. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31892. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31893. // First island of uv mapping
  31894. // v = 4h 3+ 2
  31895. // v = 3h 9+ 4
  31896. // v = 2h 9+ 5 B
  31897. // v = 1h 9 1 0
  31898. // v = 0h 3 8 7 A
  31899. // u = 0 1 2 3 4 5 6 *a
  31900. // Second island of uv mapping
  31901. // v = 4h 0+ B+ 4+
  31902. // v = 3h A+ 2+
  31903. // v = 2h 7+ 6 3+
  31904. // v = 1h 8+ 3+
  31905. // v = 0h
  31906. // u = 0 1 2 3 4 5 6 *a
  31907. // Face layout on texture UV mapping
  31908. // ============
  31909. // \ 4 /\ 16 / ======
  31910. // \ / \ / /\ 11 /
  31911. // \/ 7 \/ / \ /
  31912. // ======= / 10 \/
  31913. // /\ 17 /\ =======
  31914. // / \ / \ \ 15 /\
  31915. // / 8 \/ 12 \ \ / \
  31916. // ============ \/ 6 \
  31917. // \ 18 /\ ============
  31918. // \ / \ \ 5 /\ 0 /
  31919. // \/ 13 \ \ / \ /
  31920. // ======= \/ 1 \/
  31921. // =============
  31922. // /\ 19 /\ 2 /\
  31923. // / \ / \ / \
  31924. // / 14 \/ 9 \/ 3 \
  31925. // ===================
  31926. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31927. var ustep = 138 / 1024;
  31928. var vstep = 239 / 1024;
  31929. var uoffset = 60 / 1024;
  31930. var voffset = 26 / 1024;
  31931. // Second island should have margin, not to touch the first island
  31932. // avoid any borderline artefact in pixel rounding
  31933. var island_u_offset = -40 / 1024;
  31934. var island_v_offset = +20 / 1024;
  31935. // face is either island 0 or 1 :
  31936. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31937. var island = [
  31938. 0, 0, 0, 0, 1,
  31939. 0, 0, 1, 1, 0,
  31940. 0, 0, 1, 1, 0,
  31941. 0, 1, 1, 1, 0 // 15 - 19
  31942. ];
  31943. var indices = new Array();
  31944. var positions = new Array();
  31945. var normals = new Array();
  31946. var uvs = new Array();
  31947. var current_indice = 0;
  31948. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31949. var face_vertex_pos = new Array(3);
  31950. var face_vertex_uv = new Array(3);
  31951. var v012;
  31952. for (v012 = 0; v012 < 3; v012++) {
  31953. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31954. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31955. }
  31956. // create all with normals
  31957. for (var face = 0; face < 20; face++) {
  31958. // 3 vertex per face
  31959. for (v012 = 0; v012 < 3; v012++) {
  31960. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31961. var v_id = ico_indices[3 * face + v012];
  31962. // vertex have 3D position (x,y,z)
  31963. 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]);
  31964. // Normalize to get normal, then scale to radius
  31965. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31966. // uv Coordinates from vertex ID
  31967. 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);
  31968. }
  31969. // Subdivide the face (interpolate pos, norm, uv)
  31970. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31971. // - norm is linear interpolation of vertex corner normal
  31972. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31973. // - uv is linear interpolation
  31974. //
  31975. // Topology is as below for sub-divide by 2
  31976. // vertex shown as v0,v1,v2
  31977. // interp index is i1 to progress in range [v0,v1[
  31978. // interp index is i2 to progress in range [v0,v2[
  31979. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31980. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31981. //
  31982. //
  31983. // i2 v2
  31984. // ^ ^
  31985. // / / \
  31986. // / / \
  31987. // / / \
  31988. // / / (0,1) \
  31989. // / #---------\
  31990. // / / \ (0,0)'/ \
  31991. // / / \ / \
  31992. // / / \ / \
  31993. // / / (0,0) \ / (1,0) \
  31994. // / #---------#---------\
  31995. // v0 v1
  31996. //
  31997. // --------------------> i1
  31998. //
  31999. // interp of (i1,i2):
  32000. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32001. // along i1 : lerp(x0,x1, i1/(S-i2))
  32002. //
  32003. // centroid of triangle is needed to get help normal computation
  32004. // (c1,c2) are used for centroid location
  32005. var interp_vertex = function (i1, i2, c1, c2) {
  32006. // vertex is interpolated from
  32007. // - face_vertex_pos[0..2]
  32008. // - face_vertex_uv[0..2]
  32009. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32010. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32011. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32012. pos_interp.normalize();
  32013. var vertex_normal;
  32014. if (flat) {
  32015. // in flat mode, recalculate normal as face centroid normal
  32016. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32017. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32018. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32019. }
  32020. else {
  32021. // in smooth mode, recalculate normal from each single vertex position
  32022. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32023. }
  32024. // Vertex normal need correction due to X,Y,Z radius scaling
  32025. vertex_normal.x /= radiusX;
  32026. vertex_normal.y /= radiusY;
  32027. vertex_normal.z /= radiusZ;
  32028. vertex_normal.normalize();
  32029. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32030. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32031. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32032. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32033. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32034. uvs.push(uv_interp.x, uv_interp.y);
  32035. // push each vertex has member of a face
  32036. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32037. indices.push(current_indice);
  32038. current_indice++;
  32039. };
  32040. for (var i2 = 0; i2 < subdivisions; i2++) {
  32041. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32042. // face : (i1,i2) for /\ :
  32043. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32044. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32045. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32046. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32047. if (i1 + i2 + 1 < subdivisions) {
  32048. // face : (i1,i2)' for \/ :
  32049. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32050. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32051. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32052. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32053. }
  32054. }
  32055. }
  32056. }
  32057. // Sides
  32058. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32059. // Result
  32060. var vertexData = new VertexData();
  32061. vertexData.indices = indices;
  32062. vertexData.positions = positions;
  32063. vertexData.normals = normals;
  32064. vertexData.uvs = uvs;
  32065. return vertexData;
  32066. };
  32067. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32068. /**
  32069. * Creates the VertexData of the Polyhedron.
  32070. */
  32071. VertexData.CreatePolyhedron = function (options) {
  32072. // provided polyhedron types :
  32073. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32074. // 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)
  32075. var polyhedra = [];
  32076. 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]] };
  32077. 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]] };
  32078. polyhedra[2] = {
  32079. 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]],
  32080. 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]]
  32081. };
  32082. polyhedra[3] = {
  32083. 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]],
  32084. 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]]
  32085. };
  32086. polyhedra[4] = {
  32087. 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]],
  32088. 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]]
  32089. };
  32090. 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]] };
  32091. 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]] };
  32092. 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]] };
  32093. 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]] };
  32094. 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]] };
  32095. 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]] };
  32096. 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]] };
  32097. 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]] };
  32098. 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]] };
  32099. polyhedra[14] = {
  32100. 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]],
  32101. 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]]
  32102. };
  32103. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32104. var size = options.size;
  32105. var sizeX = options.sizeX || size || 1;
  32106. var sizeY = options.sizeY || size || 1;
  32107. var sizeZ = options.sizeZ || size || 1;
  32108. var data = options.custom || polyhedra[type];
  32109. var nbfaces = data.face.length;
  32110. var faceUV = options.faceUV || new Array(nbfaces);
  32111. var faceColors = options.faceColors;
  32112. var flat = (options.flat === undefined) ? true : options.flat;
  32113. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32114. var positions = new Array();
  32115. var indices = new Array();
  32116. var normals = new Array();
  32117. var uvs = new Array();
  32118. var colors = new Array();
  32119. var index = 0;
  32120. var faceIdx = 0; // face cursor in the array "indexes"
  32121. var indexes = new Array();
  32122. var i = 0;
  32123. var f = 0;
  32124. var u, v, ang, x, y, tmp;
  32125. // default face colors and UV if undefined
  32126. if (flat) {
  32127. for (f = 0; f < nbfaces; f++) {
  32128. if (faceColors && faceColors[f] === undefined) {
  32129. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32130. }
  32131. if (faceUV && faceUV[f] === undefined) {
  32132. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32133. }
  32134. }
  32135. }
  32136. if (!flat) {
  32137. for (i = 0; i < data.vertex.length; i++) {
  32138. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32139. uvs.push(0, 0);
  32140. }
  32141. for (f = 0; f < nbfaces; f++) {
  32142. for (i = 0; i < data.face[f].length - 2; i++) {
  32143. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32144. }
  32145. }
  32146. }
  32147. else {
  32148. for (f = 0; f < nbfaces; f++) {
  32149. var fl = data.face[f].length; // number of vertices of the current face
  32150. ang = 2 * Math.PI / fl;
  32151. x = 0.5 * Math.tan(ang / 2);
  32152. y = 0.5;
  32153. // positions, uvs, colors
  32154. for (i = 0; i < fl; i++) {
  32155. // positions
  32156. 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);
  32157. indexes.push(index);
  32158. index++;
  32159. // uvs
  32160. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32161. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32162. uvs.push(u, v);
  32163. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32164. y = x * Math.sin(ang) + y * Math.cos(ang);
  32165. x = tmp;
  32166. // colors
  32167. if (faceColors) {
  32168. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32169. }
  32170. }
  32171. // indices from indexes
  32172. for (i = 0; i < fl - 2; i++) {
  32173. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32174. }
  32175. faceIdx += fl;
  32176. }
  32177. }
  32178. VertexData.ComputeNormals(positions, indices, normals);
  32179. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32180. var vertexData = new VertexData();
  32181. vertexData.positions = positions;
  32182. vertexData.indices = indices;
  32183. vertexData.normals = normals;
  32184. vertexData.uvs = uvs;
  32185. if (faceColors && flat) {
  32186. vertexData.colors = colors;
  32187. }
  32188. return vertexData;
  32189. };
  32190. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32191. /**
  32192. * Creates the VertexData of the Torus Knot.
  32193. */
  32194. VertexData.CreateTorusKnot = function (options) {
  32195. var indices = new Array();
  32196. var positions = new Array();
  32197. var normals = new Array();
  32198. var uvs = new Array();
  32199. var radius = options.radius || 2;
  32200. var tube = options.tube || 0.5;
  32201. var radialSegments = options.radialSegments || 32;
  32202. var tubularSegments = options.tubularSegments || 32;
  32203. var p = options.p || 2;
  32204. var q = options.q || 3;
  32205. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32206. // Helper
  32207. var getPos = function (angle) {
  32208. var cu = Math.cos(angle);
  32209. var su = Math.sin(angle);
  32210. var quOverP = q / p * angle;
  32211. var cs = Math.cos(quOverP);
  32212. var tx = radius * (2 + cs) * 0.5 * cu;
  32213. var ty = radius * (2 + cs) * su * 0.5;
  32214. var tz = radius * Math.sin(quOverP) * 0.5;
  32215. return new BABYLON.Vector3(tx, ty, tz);
  32216. };
  32217. // Vertices
  32218. var i;
  32219. var j;
  32220. for (i = 0; i <= radialSegments; i++) {
  32221. var modI = i % radialSegments;
  32222. var u = modI / radialSegments * 2 * p * Math.PI;
  32223. var p1 = getPos(u);
  32224. var p2 = getPos(u + 0.01);
  32225. var tang = p2.subtract(p1);
  32226. var n = p2.add(p1);
  32227. var bitan = BABYLON.Vector3.Cross(tang, n);
  32228. n = BABYLON.Vector3.Cross(bitan, tang);
  32229. bitan.normalize();
  32230. n.normalize();
  32231. for (j = 0; j < tubularSegments; j++) {
  32232. var modJ = j % tubularSegments;
  32233. var v = modJ / tubularSegments * 2 * Math.PI;
  32234. var cx = -tube * Math.cos(v);
  32235. var cy = tube * Math.sin(v);
  32236. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32237. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32238. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32239. uvs.push(i / radialSegments);
  32240. uvs.push(j / tubularSegments);
  32241. }
  32242. }
  32243. for (i = 0; i < radialSegments; i++) {
  32244. for (j = 0; j < tubularSegments; j++) {
  32245. var jNext = (j + 1) % tubularSegments;
  32246. var a = i * tubularSegments + j;
  32247. var b = (i + 1) * tubularSegments + j;
  32248. var c = (i + 1) * tubularSegments + jNext;
  32249. var d = i * tubularSegments + jNext;
  32250. indices.push(d);
  32251. indices.push(b);
  32252. indices.push(a);
  32253. indices.push(d);
  32254. indices.push(c);
  32255. indices.push(b);
  32256. }
  32257. }
  32258. // Normals
  32259. VertexData.ComputeNormals(positions, indices, normals);
  32260. // Sides
  32261. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32262. // Result
  32263. var vertexData = new VertexData();
  32264. vertexData.indices = indices;
  32265. vertexData.positions = positions;
  32266. vertexData.normals = normals;
  32267. vertexData.uvs = uvs;
  32268. return vertexData;
  32269. };
  32270. // Tools
  32271. /**
  32272. * @param {any} - positions (number[] or Float32Array)
  32273. * @param {any} - indices (number[] or Uint16Array)
  32274. * @param {any} - normals (number[] or Float32Array)
  32275. * options (optional) :
  32276. * facetPositions : optional array of facet positions (vector3)
  32277. * facetNormals : optional array of facet normals (vector3)
  32278. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  32279. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  32280. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  32281. * bbSize : optional bounding box size data, required for facetPartitioning computation
  32282. * bInfo : optional bounding info, required for facetPartitioning computation
  32283. * useRightHandedSystem: optional boolean to for right handed system computation
  32284. * depthSort : optional boolean to enable the facet depth sort computation
  32285. * distanceTo : optional Vector3 to compute the facet depth from this location
  32286. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  32287. */
  32288. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  32289. // temporary scalar variables
  32290. var index = 0; // facet index
  32291. var p1p2x = 0.0; // p1p2 vector x coordinate
  32292. var p1p2y = 0.0; // p1p2 vector y coordinate
  32293. var p1p2z = 0.0; // p1p2 vector z coordinate
  32294. var p3p2x = 0.0; // p3p2 vector x coordinate
  32295. var p3p2y = 0.0; // p3p2 vector y coordinate
  32296. var p3p2z = 0.0; // p3p2 vector z coordinate
  32297. var faceNormalx = 0.0; // facet normal x coordinate
  32298. var faceNormaly = 0.0; // facet normal y coordinate
  32299. var faceNormalz = 0.0; // facet normal z coordinate
  32300. var length = 0.0; // facet normal length before normalization
  32301. var v1x = 0; // vector1 x index in the positions array
  32302. var v1y = 0; // vector1 y index in the positions array
  32303. var v1z = 0; // vector1 z index in the positions array
  32304. var v2x = 0; // vector2 x index in the positions array
  32305. var v2y = 0; // vector2 y index in the positions array
  32306. var v2z = 0; // vector2 z index in the positions array
  32307. var v3x = 0; // vector3 x index in the positions array
  32308. var v3y = 0; // vector3 y index in the positions array
  32309. var v3z = 0; // vector3 z index in the positions array
  32310. var computeFacetNormals = false;
  32311. var computeFacetPositions = false;
  32312. var computeFacetPartitioning = false;
  32313. var computeDepthSort = false;
  32314. var faceNormalSign = 1;
  32315. var ratio = 0;
  32316. var distanceTo = null;
  32317. if (options) {
  32318. computeFacetNormals = (options.facetNormals) ? true : false;
  32319. computeFacetPositions = (options.facetPositions) ? true : false;
  32320. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  32321. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  32322. ratio = options.ratio || 0;
  32323. computeDepthSort = (options.depthSort) ? true : false;
  32324. distanceTo = (options.distanceTo);
  32325. if (computeDepthSort) {
  32326. if (distanceTo === undefined) {
  32327. distanceTo = BABYLON.Vector3.Zero();
  32328. }
  32329. var depthSortedFacets = options.depthSortedFacets;
  32330. }
  32331. }
  32332. // facetPartitioning reinit if needed
  32333. var xSubRatio = 0;
  32334. var ySubRatio = 0;
  32335. var zSubRatio = 0;
  32336. var subSq = 0;
  32337. if (computeFacetPartitioning && options && options.bbSize) {
  32338. var ox = 0; // X partitioning index for facet position
  32339. var oy = 0; // Y partinioning index for facet position
  32340. var oz = 0; // Z partinioning index for facet position
  32341. var b1x = 0; // X partitioning index for facet v1 vertex
  32342. var b1y = 0; // Y partitioning index for facet v1 vertex
  32343. var b1z = 0; // z partitioning index for facet v1 vertex
  32344. var b2x = 0; // X partitioning index for facet v2 vertex
  32345. var b2y = 0; // Y partitioning index for facet v2 vertex
  32346. var b2z = 0; // Z partitioning index for facet v2 vertex
  32347. var b3x = 0; // X partitioning index for facet v3 vertex
  32348. var b3y = 0; // Y partitioning index for facet v3 vertex
  32349. var b3z = 0; // Z partitioning index for facet v3 vertex
  32350. var block_idx_o = 0; // facet barycenter block index
  32351. var block_idx_v1 = 0; // v1 vertex block index
  32352. var block_idx_v2 = 0; // v2 vertex block index
  32353. var block_idx_v3 = 0; // v3 vertex block index
  32354. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  32355. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  32356. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  32357. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  32358. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  32359. subSq = options.subDiv.max * options.subDiv.max;
  32360. options.facetPartitioning.length = 0;
  32361. }
  32362. // reset the normals
  32363. for (index = 0; index < positions.length; index++) {
  32364. normals[index] = 0.0;
  32365. }
  32366. // Loop : 1 indice triplet = 1 facet
  32367. var nbFaces = (indices.length / 3) | 0;
  32368. for (index = 0; index < nbFaces; index++) {
  32369. // get the indexes of the coordinates of each vertex of the facet
  32370. v1x = indices[index * 3] * 3;
  32371. v1y = v1x + 1;
  32372. v1z = v1x + 2;
  32373. v2x = indices[index * 3 + 1] * 3;
  32374. v2y = v2x + 1;
  32375. v2z = v2x + 2;
  32376. v3x = indices[index * 3 + 2] * 3;
  32377. v3y = v3x + 1;
  32378. v3z = v3x + 2;
  32379. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  32380. p1p2y = positions[v1y] - positions[v2y];
  32381. p1p2z = positions[v1z] - positions[v2z];
  32382. p3p2x = positions[v3x] - positions[v2x];
  32383. p3p2y = positions[v3y] - positions[v2y];
  32384. p3p2z = positions[v3z] - positions[v2z];
  32385. // compute the face normal with the cross product
  32386. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32387. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32388. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32389. // normalize this normal and store it in the array facetData
  32390. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32391. length = (length === 0) ? 1.0 : length;
  32392. faceNormalx /= length;
  32393. faceNormaly /= length;
  32394. faceNormalz /= length;
  32395. if (computeFacetNormals && options) {
  32396. options.facetNormals[index].x = faceNormalx;
  32397. options.facetNormals[index].y = faceNormaly;
  32398. options.facetNormals[index].z = faceNormalz;
  32399. }
  32400. if (computeFacetPositions && options) {
  32401. // compute and the facet barycenter coordinates in the array facetPositions
  32402. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32403. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32404. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32405. }
  32406. if (computeFacetPartitioning && options) {
  32407. // store the facet indexes in arrays in the main facetPartitioning array :
  32408. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32409. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32410. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32411. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32412. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32413. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32414. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32415. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32416. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32417. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32418. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32419. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32420. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32421. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32422. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32423. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32424. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32425. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32426. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32427. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32428. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32429. // push each facet index in each block containing the vertex
  32430. options.facetPartitioning[block_idx_v1].push(index);
  32431. if (block_idx_v2 != block_idx_v1) {
  32432. options.facetPartitioning[block_idx_v2].push(index);
  32433. }
  32434. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32435. options.facetPartitioning[block_idx_v3].push(index);
  32436. }
  32437. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32438. options.facetPartitioning[block_idx_o].push(index);
  32439. }
  32440. }
  32441. if (computeDepthSort && options && options.facetPositions) {
  32442. var dsf = depthSortedFacets[index];
  32443. dsf.ind = index * 3;
  32444. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32445. }
  32446. // compute the normals anyway
  32447. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32448. normals[v1y] += faceNormaly;
  32449. normals[v1z] += faceNormalz;
  32450. normals[v2x] += faceNormalx;
  32451. normals[v2y] += faceNormaly;
  32452. normals[v2z] += faceNormalz;
  32453. normals[v3x] += faceNormalx;
  32454. normals[v3y] += faceNormaly;
  32455. normals[v3z] += faceNormalz;
  32456. }
  32457. // last normalization of each normal
  32458. for (index = 0; index < normals.length / 3; index++) {
  32459. faceNormalx = normals[index * 3];
  32460. faceNormaly = normals[index * 3 + 1];
  32461. faceNormalz = normals[index * 3 + 2];
  32462. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32463. length = (length === 0) ? 1.0 : length;
  32464. faceNormalx /= length;
  32465. faceNormaly /= length;
  32466. faceNormalz /= length;
  32467. normals[index * 3] = faceNormalx;
  32468. normals[index * 3 + 1] = faceNormaly;
  32469. normals[index * 3 + 2] = faceNormalz;
  32470. }
  32471. };
  32472. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32473. var li = indices.length;
  32474. var ln = normals.length;
  32475. var i;
  32476. var n;
  32477. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32478. switch (sideOrientation) {
  32479. case BABYLON.Mesh.FRONTSIDE:
  32480. // nothing changed
  32481. break;
  32482. case BABYLON.Mesh.BACKSIDE:
  32483. var tmp;
  32484. // indices
  32485. for (i = 0; i < li; i += 3) {
  32486. tmp = indices[i];
  32487. indices[i] = indices[i + 2];
  32488. indices[i + 2] = tmp;
  32489. }
  32490. // normals
  32491. for (n = 0; n < ln; n++) {
  32492. normals[n] = -normals[n];
  32493. }
  32494. break;
  32495. case BABYLON.Mesh.DOUBLESIDE:
  32496. // positions
  32497. var lp = positions.length;
  32498. var l = lp / 3;
  32499. for (var p = 0; p < lp; p++) {
  32500. positions[lp + p] = positions[p];
  32501. }
  32502. // indices
  32503. for (i = 0; i < li; i += 3) {
  32504. indices[i + li] = indices[i + 2] + l;
  32505. indices[i + 1 + li] = indices[i + 1] + l;
  32506. indices[i + 2 + li] = indices[i] + l;
  32507. }
  32508. // normals
  32509. for (n = 0; n < ln; n++) {
  32510. normals[ln + n] = -normals[n];
  32511. }
  32512. // uvs
  32513. var lu = uvs.length;
  32514. var u = 0;
  32515. for (u = 0; u < lu; u++) {
  32516. uvs[u + lu] = uvs[u];
  32517. }
  32518. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32519. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32520. u = 0;
  32521. for (i = 0; i < lu / 2; i++) {
  32522. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32523. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32524. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32525. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32526. u += 2;
  32527. }
  32528. break;
  32529. }
  32530. };
  32531. /**
  32532. * Creates a new VertexData from the imported parameters.
  32533. */
  32534. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32535. var vertexData = new VertexData();
  32536. // positions
  32537. var positions = parsedVertexData.positions;
  32538. if (positions) {
  32539. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32540. }
  32541. // normals
  32542. var normals = parsedVertexData.normals;
  32543. if (normals) {
  32544. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32545. }
  32546. // tangents
  32547. var tangents = parsedVertexData.tangents;
  32548. if (tangents) {
  32549. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32550. }
  32551. // uvs
  32552. var uvs = parsedVertexData.uvs;
  32553. if (uvs) {
  32554. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32555. }
  32556. // uv2s
  32557. var uv2s = parsedVertexData.uv2s;
  32558. if (uv2s) {
  32559. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32560. }
  32561. // uv3s
  32562. var uv3s = parsedVertexData.uv3s;
  32563. if (uv3s) {
  32564. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32565. }
  32566. // uv4s
  32567. var uv4s = parsedVertexData.uv4s;
  32568. if (uv4s) {
  32569. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32570. }
  32571. // uv5s
  32572. var uv5s = parsedVertexData.uv5s;
  32573. if (uv5s) {
  32574. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32575. }
  32576. // uv6s
  32577. var uv6s = parsedVertexData.uv6s;
  32578. if (uv6s) {
  32579. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32580. }
  32581. // colors
  32582. var colors = parsedVertexData.colors;
  32583. if (colors) {
  32584. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32585. }
  32586. // matricesIndices
  32587. var matricesIndices = parsedVertexData.matricesIndices;
  32588. if (matricesIndices) {
  32589. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32590. }
  32591. // matricesWeights
  32592. var matricesWeights = parsedVertexData.matricesWeights;
  32593. if (matricesWeights) {
  32594. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32595. }
  32596. // indices
  32597. var indices = parsedVertexData.indices;
  32598. if (indices) {
  32599. vertexData.indices = indices;
  32600. }
  32601. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32602. };
  32603. return VertexData;
  32604. }());
  32605. BABYLON.VertexData = VertexData;
  32606. })(BABYLON || (BABYLON = {}));
  32607. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32608. var BABYLON;
  32609. (function (BABYLON) {
  32610. /**
  32611. * Class used to store geometry data (vertex buffers + index buffer)
  32612. */
  32613. var Geometry = /** @class */ (function () {
  32614. /**
  32615. * Creates a new geometry
  32616. * @param id defines the unique ID
  32617. * @param scene defines the hosting scene
  32618. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32619. * @param updatable defines if geometry must be updatable (false by default)
  32620. * @param mesh defines the mesh that will be associated with the geometry
  32621. */
  32622. function Geometry(id, scene, vertexData, updatable, mesh) {
  32623. if (updatable === void 0) { updatable = false; }
  32624. if (mesh === void 0) { mesh = null; }
  32625. /**
  32626. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32627. */
  32628. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32629. this._totalVertices = 0;
  32630. this._isDisposed = false;
  32631. this._indexBufferIsUpdatable = false;
  32632. this.id = id;
  32633. this._engine = scene.getEngine();
  32634. this._meshes = [];
  32635. this._scene = scene;
  32636. //Init vertex buffer cache
  32637. this._vertexBuffers = {};
  32638. this._indices = [];
  32639. this._updatable = updatable;
  32640. // vertexData
  32641. if (vertexData) {
  32642. this.setAllVerticesData(vertexData, updatable);
  32643. }
  32644. else {
  32645. this._totalVertices = 0;
  32646. this._indices = [];
  32647. }
  32648. if (this._engine.getCaps().vertexArrayObject) {
  32649. this._vertexArrayObjects = {};
  32650. }
  32651. // applyToMesh
  32652. if (mesh) {
  32653. if (mesh.getClassName() === "LinesMesh") {
  32654. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32655. this.updateExtend();
  32656. }
  32657. this.applyToMesh(mesh);
  32658. mesh.computeWorldMatrix(true);
  32659. }
  32660. }
  32661. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32662. /**
  32663. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  32664. */
  32665. get: function () {
  32666. return this._boundingBias;
  32667. },
  32668. /**
  32669. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  32670. */
  32671. set: function (value) {
  32672. if (this._boundingBias && this._boundingBias.equals(value)) {
  32673. return;
  32674. }
  32675. this._boundingBias = value.clone();
  32676. this.updateBoundingInfo(true, null);
  32677. },
  32678. enumerable: true,
  32679. configurable: true
  32680. });
  32681. /**
  32682. * Static function used to attach a new empty geometry to a mesh
  32683. * @param mesh defines the mesh to attach the geometry to
  32684. * @returns the new {BABYLON.Geometry}
  32685. */
  32686. Geometry.CreateGeometryForMesh = function (mesh) {
  32687. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32688. geometry.applyToMesh(mesh);
  32689. return geometry;
  32690. };
  32691. Object.defineProperty(Geometry.prototype, "extend", {
  32692. /**
  32693. * Gets the current extend of the geometry
  32694. */
  32695. get: function () {
  32696. return this._extend;
  32697. },
  32698. enumerable: true,
  32699. configurable: true
  32700. });
  32701. /**
  32702. * Gets the hosting scene
  32703. * @returns the hosting {BABYLON.Scene}
  32704. */
  32705. Geometry.prototype.getScene = function () {
  32706. return this._scene;
  32707. };
  32708. /**
  32709. * Gets the hosting engine
  32710. * @returns the hosting {BABYLON.Engine}
  32711. */
  32712. Geometry.prototype.getEngine = function () {
  32713. return this._engine;
  32714. };
  32715. /**
  32716. * Defines if the geometry is ready to use
  32717. * @returns true if the geometry is ready to be used
  32718. */
  32719. Geometry.prototype.isReady = function () {
  32720. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32721. };
  32722. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32723. /**
  32724. * Gets a value indicating that the geometry should not be serialized
  32725. */
  32726. get: function () {
  32727. for (var index = 0; index < this._meshes.length; index++) {
  32728. if (!this._meshes[index].doNotSerialize) {
  32729. return false;
  32730. }
  32731. }
  32732. return true;
  32733. },
  32734. enumerable: true,
  32735. configurable: true
  32736. });
  32737. /** @ignore */
  32738. Geometry.prototype._rebuild = function () {
  32739. if (this._vertexArrayObjects) {
  32740. this._vertexArrayObjects = {};
  32741. }
  32742. // Index buffer
  32743. if (this._meshes.length !== 0 && this._indices) {
  32744. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32745. }
  32746. // Vertex buffers
  32747. for (var key in this._vertexBuffers) {
  32748. var vertexBuffer = this._vertexBuffers[key];
  32749. vertexBuffer._rebuild();
  32750. }
  32751. };
  32752. /**
  32753. * Affects all gemetry data in one call
  32754. * @param vertexData defines the geometry data
  32755. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32756. */
  32757. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32758. vertexData.applyToGeometry(this, updatable);
  32759. this.notifyUpdate();
  32760. };
  32761. /**
  32762. * Set specific vertex data
  32763. * @param kind defines the data kind (Position, normal, etc...)
  32764. * @param data defines the vertex data to use
  32765. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32766. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32767. */
  32768. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32769. if (updatable === void 0) { updatable = false; }
  32770. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32771. this.setVerticesBuffer(buffer);
  32772. };
  32773. /**
  32774. * Removes a specific vertex data
  32775. * @param kind defines the data kind (Position, normal, etc...)
  32776. */
  32777. Geometry.prototype.removeVerticesData = function (kind) {
  32778. if (this._vertexBuffers[kind]) {
  32779. this._vertexBuffers[kind].dispose();
  32780. delete this._vertexBuffers[kind];
  32781. }
  32782. };
  32783. /**
  32784. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32785. * @param buffer defines the vertex buffer to use
  32786. */
  32787. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32788. var kind = buffer.getKind();
  32789. if (this._vertexBuffers[kind]) {
  32790. this._vertexBuffers[kind].dispose();
  32791. }
  32792. this._vertexBuffers[kind] = buffer;
  32793. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32794. var data = buffer.getData();
  32795. var stride = buffer.getStrideSize();
  32796. this._totalVertices = data.length / stride;
  32797. this.updateExtend(data, stride);
  32798. this._resetPointsArrayCache();
  32799. var meshes = this._meshes;
  32800. var numOfMeshes = meshes.length;
  32801. for (var index = 0; index < numOfMeshes; index++) {
  32802. var mesh = meshes[index];
  32803. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32804. mesh._createGlobalSubMesh(false);
  32805. mesh.computeWorldMatrix(true);
  32806. }
  32807. }
  32808. this.notifyUpdate(kind);
  32809. if (this._vertexArrayObjects) {
  32810. this._disposeVertexArrayObjects();
  32811. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32812. }
  32813. };
  32814. /**
  32815. * Update a specific vertex buffer
  32816. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32817. * It will do nothing if the buffer is not updatable
  32818. * @param kind defines the data kind (Position, normal, etc...)
  32819. * @param data defines the data to use
  32820. * @param offset defines the offset in the target buffer where to store the data
  32821. */
  32822. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32823. var vertexBuffer = this.getVertexBuffer(kind);
  32824. if (!vertexBuffer) {
  32825. return;
  32826. }
  32827. vertexBuffer.updateDirectly(data, offset);
  32828. this.notifyUpdate(kind);
  32829. };
  32830. /**
  32831. * Update a specific vertex buffer
  32832. * This function will create a new buffer if the current one is not updatable
  32833. * @param kind defines the data kind (Position, normal, etc...)
  32834. * @param data defines the data to use
  32835. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32836. */
  32837. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32838. if (updateExtends === void 0) { updateExtends = false; }
  32839. var vertexBuffer = this.getVertexBuffer(kind);
  32840. if (!vertexBuffer) {
  32841. return;
  32842. }
  32843. vertexBuffer.update(data);
  32844. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32845. var stride = vertexBuffer.getStrideSize();
  32846. this._totalVertices = data.length / stride;
  32847. this.updateBoundingInfo(updateExtends, data);
  32848. }
  32849. this.notifyUpdate(kind);
  32850. };
  32851. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32852. if (updateExtends) {
  32853. this.updateExtend(data);
  32854. }
  32855. var meshes = this._meshes;
  32856. var numOfMeshes = meshes.length;
  32857. this._resetPointsArrayCache();
  32858. for (var index = 0; index < numOfMeshes; index++) {
  32859. var mesh = meshes[index];
  32860. if (updateExtends) {
  32861. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32862. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32863. var subMesh = mesh.subMeshes[subIndex];
  32864. subMesh.refreshBoundingInfo();
  32865. }
  32866. }
  32867. }
  32868. };
  32869. /** @ignore */
  32870. Geometry.prototype._bind = function (effect, indexToBind) {
  32871. if (!effect) {
  32872. return;
  32873. }
  32874. if (indexToBind === undefined) {
  32875. indexToBind = this._indexBuffer;
  32876. }
  32877. var vbs = this.getVertexBuffers();
  32878. if (!vbs) {
  32879. return;
  32880. }
  32881. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32882. this._engine.bindBuffers(vbs, indexToBind, effect);
  32883. return;
  32884. }
  32885. // Using VAO
  32886. if (!this._vertexArrayObjects[effect.key]) {
  32887. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32888. }
  32889. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32890. };
  32891. /**
  32892. * Gets total number of vertices
  32893. * @returns the total number of vertices
  32894. */
  32895. Geometry.prototype.getTotalVertices = function () {
  32896. if (!this.isReady()) {
  32897. return 0;
  32898. }
  32899. return this._totalVertices;
  32900. };
  32901. /**
  32902. * Gets a specific vertex data attached to this geometry
  32903. * @param kind defines the data kind (Position, normal, etc...)
  32904. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32905. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32906. * @returns a float array containing vertex data
  32907. */
  32908. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32909. var vertexBuffer = this.getVertexBuffer(kind);
  32910. if (!vertexBuffer) {
  32911. return null;
  32912. }
  32913. var orig = vertexBuffer.getData();
  32914. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32915. return orig;
  32916. }
  32917. else {
  32918. var len = orig.length;
  32919. var copy = [];
  32920. for (var i = 0; i < len; i++) {
  32921. copy.push(orig[i]);
  32922. }
  32923. return copy;
  32924. }
  32925. };
  32926. /**
  32927. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32928. * @param kind defines the data kind (Position, normal, etc...)
  32929. * @returns true if the vertex buffer with the specified kind is updatable
  32930. */
  32931. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32932. var vb = this._vertexBuffers[kind];
  32933. if (!vb) {
  32934. return false;
  32935. }
  32936. return vb.isUpdatable();
  32937. };
  32938. /**
  32939. * Gets a specific vertex buffer
  32940. * @param kind defines the data kind (Position, normal, etc...)
  32941. * @returns a {BABYLON.VertexBuffer}
  32942. */
  32943. Geometry.prototype.getVertexBuffer = function (kind) {
  32944. if (!this.isReady()) {
  32945. return null;
  32946. }
  32947. return this._vertexBuffers[kind];
  32948. };
  32949. /**
  32950. * Returns all vertex buffers
  32951. * @return an object holding all vertex buffers indexed by kind
  32952. */
  32953. Geometry.prototype.getVertexBuffers = function () {
  32954. if (!this.isReady()) {
  32955. return null;
  32956. }
  32957. return this._vertexBuffers;
  32958. };
  32959. /**
  32960. * Gets a boolean indicating if specific vertex buffer is present
  32961. * @param kind defines the data kind (Position, normal, etc...)
  32962. * @returns true if data is present
  32963. */
  32964. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32965. if (!this._vertexBuffers) {
  32966. if (this._delayInfo) {
  32967. return this._delayInfo.indexOf(kind) !== -1;
  32968. }
  32969. return false;
  32970. }
  32971. return this._vertexBuffers[kind] !== undefined;
  32972. };
  32973. /**
  32974. * Gets a list of all attached data kinds (Position, normal, etc...)
  32975. * @returns a list of string containing all kinds
  32976. */
  32977. Geometry.prototype.getVerticesDataKinds = function () {
  32978. var result = [];
  32979. var kind;
  32980. if (!this._vertexBuffers && this._delayInfo) {
  32981. for (kind in this._delayInfo) {
  32982. result.push(kind);
  32983. }
  32984. }
  32985. else {
  32986. for (kind in this._vertexBuffers) {
  32987. result.push(kind);
  32988. }
  32989. }
  32990. return result;
  32991. };
  32992. /**
  32993. * Update index buffer
  32994. * @param indices defines the indices to store in the index buffer
  32995. * @param offset defines the offset in the target buffer where to store the data
  32996. */
  32997. Geometry.prototype.updateIndices = function (indices, offset) {
  32998. if (!this._indexBuffer) {
  32999. return;
  33000. }
  33001. if (!this._indexBufferIsUpdatable) {
  33002. this.setIndices(indices, null, true);
  33003. }
  33004. else {
  33005. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  33006. }
  33007. };
  33008. /**
  33009. * Creates a new index buffer
  33010. * @param indices defines the indices to store in the index buffer
  33011. * @param totalVertices defines the total number of vertices (could be null)
  33012. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  33013. */
  33014. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  33015. if (totalVertices === void 0) { totalVertices = null; }
  33016. if (updatable === void 0) { updatable = false; }
  33017. if (this._indexBuffer) {
  33018. this._engine._releaseBuffer(this._indexBuffer);
  33019. }
  33020. this._disposeVertexArrayObjects();
  33021. this._indices = indices;
  33022. this._indexBufferIsUpdatable = updatable;
  33023. if (this._meshes.length !== 0 && this._indices) {
  33024. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  33025. }
  33026. if (totalVertices != undefined) {
  33027. this._totalVertices = totalVertices;
  33028. }
  33029. var meshes = this._meshes;
  33030. var numOfMeshes = meshes.length;
  33031. for (var index = 0; index < numOfMeshes; index++) {
  33032. meshes[index]._createGlobalSubMesh(true);
  33033. }
  33034. this.notifyUpdate();
  33035. };
  33036. /**
  33037. * Return the total number of indices
  33038. * @returns the total number of indices
  33039. */
  33040. Geometry.prototype.getTotalIndices = function () {
  33041. if (!this.isReady()) {
  33042. return 0;
  33043. }
  33044. return this._indices.length;
  33045. };
  33046. /**
  33047. * Gets the index buffer array
  33048. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  33049. * @returns the index buffer array
  33050. */
  33051. Geometry.prototype.getIndices = function (copyWhenShared) {
  33052. if (!this.isReady()) {
  33053. return null;
  33054. }
  33055. var orig = this._indices;
  33056. if (!copyWhenShared || this._meshes.length === 1) {
  33057. return orig;
  33058. }
  33059. else {
  33060. var len = orig.length;
  33061. var copy = [];
  33062. for (var i = 0; i < len; i++) {
  33063. copy.push(orig[i]);
  33064. }
  33065. return copy;
  33066. }
  33067. };
  33068. /**
  33069. * Gets the index buffer
  33070. * @return the index buffer
  33071. */
  33072. Geometry.prototype.getIndexBuffer = function () {
  33073. if (!this.isReady()) {
  33074. return null;
  33075. }
  33076. return this._indexBuffer;
  33077. };
  33078. /** @ignore */
  33079. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  33080. if (effect === void 0) { effect = null; }
  33081. if (!effect || !this._vertexArrayObjects) {
  33082. return;
  33083. }
  33084. if (this._vertexArrayObjects[effect.key]) {
  33085. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  33086. delete this._vertexArrayObjects[effect.key];
  33087. }
  33088. };
  33089. /**
  33090. * Release the associated resources for a specific mesh
  33091. * @param mesh defines the source mesh
  33092. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  33093. */
  33094. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33095. var meshes = this._meshes;
  33096. var index = meshes.indexOf(mesh);
  33097. if (index === -1) {
  33098. return;
  33099. }
  33100. meshes.splice(index, 1);
  33101. mesh._geometry = null;
  33102. if (meshes.length === 0 && shouldDispose) {
  33103. this.dispose();
  33104. }
  33105. };
  33106. /**
  33107. * Apply current geometry to a given mesh
  33108. * @param mesh defines the mesh to apply geometry to
  33109. */
  33110. Geometry.prototype.applyToMesh = function (mesh) {
  33111. if (mesh._geometry === this) {
  33112. return;
  33113. }
  33114. var previousGeometry = mesh._geometry;
  33115. if (previousGeometry) {
  33116. previousGeometry.releaseForMesh(mesh);
  33117. }
  33118. var meshes = this._meshes;
  33119. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33120. mesh._geometry = this;
  33121. this._scene.pushGeometry(this);
  33122. meshes.push(mesh);
  33123. if (this.isReady()) {
  33124. this._applyToMesh(mesh);
  33125. }
  33126. else {
  33127. mesh._boundingInfo = this._boundingInfo;
  33128. }
  33129. };
  33130. Geometry.prototype.updateExtend = function (data, stride) {
  33131. if (data === void 0) { data = null; }
  33132. if (!data) {
  33133. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33134. }
  33135. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33136. };
  33137. Geometry.prototype._applyToMesh = function (mesh) {
  33138. var numOfMeshes = this._meshes.length;
  33139. // vertexBuffers
  33140. for (var kind in this._vertexBuffers) {
  33141. if (numOfMeshes === 1) {
  33142. this._vertexBuffers[kind].create();
  33143. }
  33144. var buffer = this._vertexBuffers[kind].getBuffer();
  33145. if (buffer)
  33146. buffer.references = numOfMeshes;
  33147. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33148. if (!this._extend) {
  33149. this.updateExtend(this._vertexBuffers[kind].getData());
  33150. }
  33151. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33152. mesh._createGlobalSubMesh(false);
  33153. //bounding info was just created again, world matrix should be applied again.
  33154. mesh._updateBoundingInfo();
  33155. }
  33156. }
  33157. // indexBuffer
  33158. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33159. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33160. }
  33161. if (this._indexBuffer) {
  33162. this._indexBuffer.references = numOfMeshes;
  33163. }
  33164. };
  33165. Geometry.prototype.notifyUpdate = function (kind) {
  33166. if (this.onGeometryUpdated) {
  33167. this.onGeometryUpdated(this, kind);
  33168. }
  33169. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  33170. var mesh = _a[_i];
  33171. mesh._markSubMeshesAsAttributesDirty();
  33172. }
  33173. };
  33174. /**
  33175. * Load the geometry if it was flagged as delay loaded
  33176. * @param scene defines the hosting scene
  33177. * @param onLoaded defines a callback called when the geometry is loaded
  33178. */
  33179. Geometry.prototype.load = function (scene, onLoaded) {
  33180. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33181. return;
  33182. }
  33183. if (this.isReady()) {
  33184. if (onLoaded) {
  33185. onLoaded();
  33186. }
  33187. return;
  33188. }
  33189. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33190. this._queueLoad(scene, onLoaded);
  33191. };
  33192. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33193. var _this = this;
  33194. if (!this.delayLoadingFile) {
  33195. return;
  33196. }
  33197. scene._addPendingData(this);
  33198. scene._loadFile(this.delayLoadingFile, function (data) {
  33199. if (!_this._delayLoadingFunction) {
  33200. return;
  33201. }
  33202. _this._delayLoadingFunction(JSON.parse(data), _this);
  33203. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33204. _this._delayInfo = [];
  33205. scene._removePendingData(_this);
  33206. var meshes = _this._meshes;
  33207. var numOfMeshes = meshes.length;
  33208. for (var index = 0; index < numOfMeshes; index++) {
  33209. _this._applyToMesh(meshes[index]);
  33210. }
  33211. if (onLoaded) {
  33212. onLoaded();
  33213. }
  33214. }, undefined, true);
  33215. };
  33216. /**
  33217. * Invert the geometry to move from a right handed system to a left handed one.
  33218. */
  33219. Geometry.prototype.toLeftHanded = function () {
  33220. // Flip faces
  33221. var tIndices = this.getIndices(false);
  33222. if (tIndices != null && tIndices.length > 0) {
  33223. for (var i = 0; i < tIndices.length; i += 3) {
  33224. var tTemp = tIndices[i + 0];
  33225. tIndices[i + 0] = tIndices[i + 2];
  33226. tIndices[i + 2] = tTemp;
  33227. }
  33228. this.setIndices(tIndices);
  33229. }
  33230. // Negate position.z
  33231. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33232. if (tPositions != null && tPositions.length > 0) {
  33233. for (var i = 0; i < tPositions.length; i += 3) {
  33234. tPositions[i + 2] = -tPositions[i + 2];
  33235. }
  33236. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33237. }
  33238. // Negate normal.z
  33239. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33240. if (tNormals != null && tNormals.length > 0) {
  33241. for (var i = 0; i < tNormals.length; i += 3) {
  33242. tNormals[i + 2] = -tNormals[i + 2];
  33243. }
  33244. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33245. }
  33246. };
  33247. // Cache
  33248. /** @ignore */
  33249. Geometry.prototype._resetPointsArrayCache = function () {
  33250. this._positions = null;
  33251. };
  33252. /** @ignore */
  33253. Geometry.prototype._generatePointsArray = function () {
  33254. if (this._positions)
  33255. return true;
  33256. this._positions = [];
  33257. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33258. if (!data) {
  33259. return false;
  33260. }
  33261. for (var index = 0; index < data.length; index += 3) {
  33262. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  33263. }
  33264. return true;
  33265. };
  33266. /**
  33267. * Gets a value indicating if the geometry is disposed
  33268. * @returns true if the geometry was disposed
  33269. */
  33270. Geometry.prototype.isDisposed = function () {
  33271. return this._isDisposed;
  33272. };
  33273. Geometry.prototype._disposeVertexArrayObjects = function () {
  33274. if (this._vertexArrayObjects) {
  33275. for (var kind in this._vertexArrayObjects) {
  33276. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  33277. }
  33278. this._vertexArrayObjects = {};
  33279. }
  33280. };
  33281. /**
  33282. * Free all associated resources
  33283. */
  33284. Geometry.prototype.dispose = function () {
  33285. var meshes = this._meshes;
  33286. var numOfMeshes = meshes.length;
  33287. var index;
  33288. for (index = 0; index < numOfMeshes; index++) {
  33289. this.releaseForMesh(meshes[index]);
  33290. }
  33291. this._meshes = [];
  33292. this._disposeVertexArrayObjects();
  33293. for (var kind in this._vertexBuffers) {
  33294. this._vertexBuffers[kind].dispose();
  33295. }
  33296. this._vertexBuffers = {};
  33297. this._totalVertices = 0;
  33298. if (this._indexBuffer) {
  33299. this._engine._releaseBuffer(this._indexBuffer);
  33300. }
  33301. this._indexBuffer = null;
  33302. this._indices = [];
  33303. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33304. this.delayLoadingFile = null;
  33305. this._delayLoadingFunction = null;
  33306. this._delayInfo = [];
  33307. this._boundingInfo = null;
  33308. this._scene.removeGeometry(this);
  33309. this._isDisposed = true;
  33310. };
  33311. /**
  33312. * Clone the current geometry into a new geometry
  33313. * @param id defines the unique ID of the new geometry
  33314. * @returns a new geometry object
  33315. */
  33316. Geometry.prototype.copy = function (id) {
  33317. var vertexData = new BABYLON.VertexData();
  33318. vertexData.indices = [];
  33319. var indices = this.getIndices();
  33320. if (indices) {
  33321. for (var index = 0; index < indices.length; index++) {
  33322. vertexData.indices.push(indices[index]);
  33323. }
  33324. }
  33325. var updatable = false;
  33326. var stopChecking = false;
  33327. var kind;
  33328. for (kind in this._vertexBuffers) {
  33329. // using slice() to make a copy of the array and not just reference it
  33330. var data = this.getVerticesData(kind);
  33331. if (data instanceof Float32Array) {
  33332. vertexData.set(new Float32Array(data), kind);
  33333. }
  33334. else {
  33335. vertexData.set(data.slice(0), kind);
  33336. }
  33337. if (!stopChecking) {
  33338. var vb = this.getVertexBuffer(kind);
  33339. if (vb) {
  33340. updatable = vb.isUpdatable();
  33341. stopChecking = !updatable;
  33342. }
  33343. }
  33344. }
  33345. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  33346. geometry.delayLoadState = this.delayLoadState;
  33347. geometry.delayLoadingFile = this.delayLoadingFile;
  33348. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33349. for (kind in this._delayInfo) {
  33350. geometry._delayInfo = geometry._delayInfo || [];
  33351. geometry._delayInfo.push(kind);
  33352. }
  33353. // Bounding info
  33354. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33355. return geometry;
  33356. };
  33357. /**
  33358. * Serialize the current geometry info (and not the vertices data) into a JSON object
  33359. * @return a JSON representation of the current geometry data (without the vertices data)
  33360. */
  33361. Geometry.prototype.serialize = function () {
  33362. var serializationObject = {};
  33363. serializationObject.id = this.id;
  33364. serializationObject.updatable = this._updatable;
  33365. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33366. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33367. }
  33368. return serializationObject;
  33369. };
  33370. Geometry.prototype.toNumberArray = function (origin) {
  33371. if (Array.isArray(origin)) {
  33372. return origin;
  33373. }
  33374. else {
  33375. return Array.prototype.slice.call(origin);
  33376. }
  33377. };
  33378. /**
  33379. * Serialize all vertices data into a JSON oject
  33380. * @returns a JSON representation of the current geometry data
  33381. */
  33382. Geometry.prototype.serializeVerticeData = function () {
  33383. var serializationObject = this.serialize();
  33384. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33385. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33386. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33387. serializationObject.positions._updatable = true;
  33388. }
  33389. }
  33390. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33391. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33392. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33393. serializationObject.normals._updatable = true;
  33394. }
  33395. }
  33396. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33397. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33398. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33399. serializationObject.tangets._updatable = true;
  33400. }
  33401. }
  33402. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33403. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33404. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33405. serializationObject.uvs._updatable = true;
  33406. }
  33407. }
  33408. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33409. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33410. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33411. serializationObject.uv2s._updatable = true;
  33412. }
  33413. }
  33414. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33415. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33416. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33417. serializationObject.uv3s._updatable = true;
  33418. }
  33419. }
  33420. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33421. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33422. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33423. serializationObject.uv4s._updatable = true;
  33424. }
  33425. }
  33426. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33427. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33428. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33429. serializationObject.uv5s._updatable = true;
  33430. }
  33431. }
  33432. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33433. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33434. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33435. serializationObject.uv6s._updatable = true;
  33436. }
  33437. }
  33438. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33439. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33440. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33441. serializationObject.colors._updatable = true;
  33442. }
  33443. }
  33444. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33445. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33446. serializationObject.matricesIndices._isExpanded = true;
  33447. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33448. serializationObject.matricesIndices._updatable = true;
  33449. }
  33450. }
  33451. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33452. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33453. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33454. serializationObject.matricesWeights._updatable = true;
  33455. }
  33456. }
  33457. serializationObject.indices = this.toNumberArray(this.getIndices());
  33458. return serializationObject;
  33459. };
  33460. // Statics
  33461. /**
  33462. * Extracts a clone of a mesh geometry
  33463. * @param mesh defines the source mesh
  33464. * @param id defines the unique ID of the new geometry object
  33465. * @returns the new geometry object
  33466. */
  33467. Geometry.ExtractFromMesh = function (mesh, id) {
  33468. var geometry = mesh._geometry;
  33469. if (!geometry) {
  33470. return null;
  33471. }
  33472. return geometry.copy(id);
  33473. };
  33474. /**
  33475. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33476. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33477. * Be aware Math.random() could cause collisions, but:
  33478. * "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"
  33479. * @returns a string containing a new GUID
  33480. */
  33481. Geometry.RandomId = function () {
  33482. return BABYLON.Tools.RandomId();
  33483. };
  33484. /** @ignore */
  33485. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33486. var scene = mesh.getScene();
  33487. // Geometry
  33488. var geometryId = parsedGeometry.geometryId;
  33489. if (geometryId) {
  33490. var geometry = scene.getGeometryByID(geometryId);
  33491. if (geometry) {
  33492. geometry.applyToMesh(mesh);
  33493. }
  33494. }
  33495. else if (parsedGeometry instanceof ArrayBuffer) {
  33496. var binaryInfo = mesh._binaryInfo;
  33497. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33498. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33499. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33500. }
  33501. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33502. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33503. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33504. }
  33505. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33506. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33507. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33508. }
  33509. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33510. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33511. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33512. }
  33513. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33514. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33515. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33516. }
  33517. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33518. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33519. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33520. }
  33521. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33522. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33523. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33524. }
  33525. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33526. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33527. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33528. }
  33529. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33530. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33531. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33532. }
  33533. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33534. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33535. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33536. }
  33537. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33538. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33539. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33540. }
  33541. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33542. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33543. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33544. }
  33545. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33546. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33547. mesh.setIndices(indicesData, null);
  33548. }
  33549. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33550. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33551. mesh.subMeshes = [];
  33552. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33553. var materialIndex = subMeshesData[(i * 5) + 0];
  33554. var verticesStart = subMeshesData[(i * 5) + 1];
  33555. var verticesCount = subMeshesData[(i * 5) + 2];
  33556. var indexStart = subMeshesData[(i * 5) + 3];
  33557. var indexCount = subMeshesData[(i * 5) + 4];
  33558. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33559. }
  33560. }
  33561. }
  33562. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33563. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33564. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33565. if (parsedGeometry.tangents) {
  33566. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33567. }
  33568. if (parsedGeometry.uvs) {
  33569. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33570. }
  33571. if (parsedGeometry.uvs2) {
  33572. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33573. }
  33574. if (parsedGeometry.uvs3) {
  33575. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33576. }
  33577. if (parsedGeometry.uvs4) {
  33578. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33579. }
  33580. if (parsedGeometry.uvs5) {
  33581. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33582. }
  33583. if (parsedGeometry.uvs6) {
  33584. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33585. }
  33586. if (parsedGeometry.colors) {
  33587. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33588. }
  33589. if (parsedGeometry.matricesIndices) {
  33590. if (!parsedGeometry.matricesIndices._isExpanded) {
  33591. var floatIndices = [];
  33592. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33593. var matricesIndex = parsedGeometry.matricesIndices[i];
  33594. floatIndices.push(matricesIndex & 0x000000FF);
  33595. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33596. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33597. floatIndices.push(matricesIndex >> 24);
  33598. }
  33599. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33600. }
  33601. else {
  33602. delete parsedGeometry.matricesIndices._isExpanded;
  33603. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33604. }
  33605. }
  33606. if (parsedGeometry.matricesIndicesExtra) {
  33607. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33608. var floatIndices = [];
  33609. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33610. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33611. floatIndices.push(matricesIndex & 0x000000FF);
  33612. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33613. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33614. floatIndices.push(matricesIndex >> 24);
  33615. }
  33616. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33617. }
  33618. else {
  33619. delete parsedGeometry.matricesIndices._isExpanded;
  33620. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33621. }
  33622. }
  33623. if (parsedGeometry.matricesWeights) {
  33624. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33625. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33626. }
  33627. if (parsedGeometry.matricesWeightsExtra) {
  33628. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33629. }
  33630. mesh.setIndices(parsedGeometry.indices, null);
  33631. }
  33632. // SubMeshes
  33633. if (parsedGeometry.subMeshes) {
  33634. mesh.subMeshes = [];
  33635. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33636. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33637. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33638. }
  33639. }
  33640. // Flat shading
  33641. if (mesh._shouldGenerateFlatShading) {
  33642. mesh.convertToFlatShadedMesh();
  33643. delete mesh._shouldGenerateFlatShading;
  33644. }
  33645. // Update
  33646. mesh.computeWorldMatrix(true);
  33647. // Octree
  33648. var sceneOctree = scene.selectionOctree;
  33649. if (sceneOctree !== undefined && sceneOctree !== null) {
  33650. sceneOctree.addMesh(mesh);
  33651. }
  33652. };
  33653. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33654. var epsilon = 1e-3;
  33655. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33656. return;
  33657. }
  33658. var noInfluenceBoneIndex = 0.0;
  33659. if (parsedGeometry.skeletonId > -1) {
  33660. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33661. if (!skeleton) {
  33662. return;
  33663. }
  33664. noInfluenceBoneIndex = skeleton.bones.length;
  33665. }
  33666. else {
  33667. return;
  33668. }
  33669. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33670. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33671. var matricesWeights = parsedGeometry.matricesWeights;
  33672. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33673. var influencers = parsedGeometry.numBoneInfluencer;
  33674. var size = matricesWeights.length;
  33675. for (var i = 0; i < size; i += 4) {
  33676. var weight = 0.0;
  33677. var firstZeroWeight = -1;
  33678. for (var j = 0; j < 4; j++) {
  33679. var w = matricesWeights[i + j];
  33680. weight += w;
  33681. if (w < epsilon && firstZeroWeight < 0) {
  33682. firstZeroWeight = j;
  33683. }
  33684. }
  33685. if (matricesWeightsExtra) {
  33686. for (var j = 0; j < 4; j++) {
  33687. var w = matricesWeightsExtra[i + j];
  33688. weight += w;
  33689. if (w < epsilon && firstZeroWeight < 0) {
  33690. firstZeroWeight = j + 4;
  33691. }
  33692. }
  33693. }
  33694. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33695. firstZeroWeight = influencers - 1;
  33696. }
  33697. if (weight > epsilon) {
  33698. var mweight = 1.0 / weight;
  33699. for (var j = 0; j < 4; j++) {
  33700. matricesWeights[i + j] *= mweight;
  33701. }
  33702. if (matricesWeightsExtra) {
  33703. for (var j = 0; j < 4; j++) {
  33704. matricesWeightsExtra[i + j] *= mweight;
  33705. }
  33706. }
  33707. }
  33708. else {
  33709. if (firstZeroWeight >= 4) {
  33710. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33711. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33712. }
  33713. else {
  33714. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33715. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33716. }
  33717. }
  33718. }
  33719. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33720. if (parsedGeometry.matricesWeightsExtra) {
  33721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33722. }
  33723. };
  33724. /**
  33725. * Create a new geometry from persisted data (Using .babylon file format)
  33726. * @param parsedVertexData defines the persisted data
  33727. * @param scene defines the hosting scene
  33728. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33729. * @returns the new geometry object
  33730. */
  33731. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33732. if (scene.getGeometryByID(parsedVertexData.id)) {
  33733. return null; // null since geometry could be something else than a box...
  33734. }
  33735. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33736. if (BABYLON.Tags) {
  33737. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33738. }
  33739. if (parsedVertexData.delayLoadingFile) {
  33740. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33741. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33742. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33743. geometry._delayInfo = [];
  33744. if (parsedVertexData.hasUVs) {
  33745. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33746. }
  33747. if (parsedVertexData.hasUVs2) {
  33748. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33749. }
  33750. if (parsedVertexData.hasUVs3) {
  33751. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33752. }
  33753. if (parsedVertexData.hasUVs4) {
  33754. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33755. }
  33756. if (parsedVertexData.hasUVs5) {
  33757. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33758. }
  33759. if (parsedVertexData.hasUVs6) {
  33760. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33761. }
  33762. if (parsedVertexData.hasColors) {
  33763. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33764. }
  33765. if (parsedVertexData.hasMatricesIndices) {
  33766. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33767. }
  33768. if (parsedVertexData.hasMatricesWeights) {
  33769. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33770. }
  33771. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33772. }
  33773. else {
  33774. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33775. }
  33776. scene.pushGeometry(geometry, true);
  33777. return geometry;
  33778. };
  33779. return Geometry;
  33780. }());
  33781. BABYLON.Geometry = Geometry;
  33782. // Primitives
  33783. /// Abstract class
  33784. /**
  33785. * Abstract class used to provide common services for all typed geometries
  33786. */
  33787. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33788. __extends(_PrimitiveGeometry, _super);
  33789. /**
  33790. * Creates a new typed geometry
  33791. * @param id defines the unique ID of the geometry
  33792. * @param scene defines the hosting scene
  33793. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33794. * @param mesh defines the hosting mesh (can be null)
  33795. */
  33796. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33797. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33798. if (mesh === void 0) { mesh = null; }
  33799. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33800. _this._canBeRegenerated = _canBeRegenerated;
  33801. _this._beingRegenerated = true;
  33802. _this.regenerate();
  33803. _this._beingRegenerated = false;
  33804. return _this;
  33805. }
  33806. /**
  33807. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33808. * @returns true if the geometry can be regenerated
  33809. */
  33810. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33811. return this._canBeRegenerated;
  33812. };
  33813. /**
  33814. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33815. */
  33816. _PrimitiveGeometry.prototype.regenerate = function () {
  33817. if (!this._canBeRegenerated) {
  33818. return;
  33819. }
  33820. this._beingRegenerated = true;
  33821. this.setAllVerticesData(this._regenerateVertexData(), false);
  33822. this._beingRegenerated = false;
  33823. };
  33824. /**
  33825. * Clone the geometry
  33826. * @param id defines the unique ID of the new geometry
  33827. * @returns the new geometry
  33828. */
  33829. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33830. return _super.prototype.copy.call(this, id);
  33831. };
  33832. // overrides
  33833. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33834. if (!this._beingRegenerated) {
  33835. return;
  33836. }
  33837. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33838. };
  33839. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33840. if (!this._beingRegenerated) {
  33841. return;
  33842. }
  33843. _super.prototype.setVerticesData.call(this, kind, data, false);
  33844. };
  33845. // to override
  33846. /** @ignore */
  33847. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33848. throw new Error("Abstract method");
  33849. };
  33850. _PrimitiveGeometry.prototype.copy = function (id) {
  33851. throw new Error("Must be overriden in sub-classes.");
  33852. };
  33853. _PrimitiveGeometry.prototype.serialize = function () {
  33854. var serializationObject = _super.prototype.serialize.call(this);
  33855. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33856. return serializationObject;
  33857. };
  33858. return _PrimitiveGeometry;
  33859. }(Geometry));
  33860. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33861. /**
  33862. * Creates a ribbon geometry
  33863. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33864. */
  33865. var RibbonGeometry = /** @class */ (function (_super) {
  33866. __extends(RibbonGeometry, _super);
  33867. /**
  33868. * Creates a ribbon geometry
  33869. * @param id defines the unique ID of the geometry
  33870. * @param scene defines the hosting scene
  33871. * @param pathArray defines the array of paths to use
  33872. * @param closeArray defines if the last path and the first path must be joined
  33873. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33874. * @param offset defines the offset between points
  33875. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33876. * @param mesh defines the hosting mesh (can be null)
  33877. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33878. */
  33879. function RibbonGeometry(id, scene,
  33880. /**
  33881. * Defines the array of paths to use
  33882. */
  33883. pathArray,
  33884. /**
  33885. * Defines if the last and first points of each path in your pathArray must be joined
  33886. */
  33887. closeArray,
  33888. /**
  33889. * Defines if the last and first points of each path in your pathArray must be joined
  33890. */
  33891. closePath,
  33892. /**
  33893. * Defines the offset between points
  33894. */
  33895. offset, canBeRegenerated, mesh,
  33896. /**
  33897. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33898. */
  33899. side) {
  33900. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33901. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33902. _this.pathArray = pathArray;
  33903. _this.closeArray = closeArray;
  33904. _this.closePath = closePath;
  33905. _this.offset = offset;
  33906. _this.side = side;
  33907. return _this;
  33908. }
  33909. /** @ignore */
  33910. RibbonGeometry.prototype._regenerateVertexData = function () {
  33911. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33912. };
  33913. RibbonGeometry.prototype.copy = function (id) {
  33914. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33915. };
  33916. return RibbonGeometry;
  33917. }(_PrimitiveGeometry));
  33918. BABYLON.RibbonGeometry = RibbonGeometry;
  33919. /**
  33920. * Creates a box geometry
  33921. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33922. */
  33923. var BoxGeometry = /** @class */ (function (_super) {
  33924. __extends(BoxGeometry, _super);
  33925. /**
  33926. * Creates a box geometry
  33927. * @param id defines the unique ID of the geometry
  33928. * @param scene defines the hosting scene
  33929. * @param size defines the zise of the box (width, height and depth are the same)
  33930. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33931. * @param mesh defines the hosting mesh (can be null)
  33932. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33933. */
  33934. function BoxGeometry(id, scene,
  33935. /**
  33936. * Defines the zise of the box (width, height and depth are the same)
  33937. */
  33938. size, canBeRegenerated, mesh,
  33939. /**
  33940. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33941. */
  33942. side) {
  33943. if (mesh === void 0) { mesh = null; }
  33944. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33945. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33946. _this.size = size;
  33947. _this.side = side;
  33948. return _this;
  33949. }
  33950. BoxGeometry.prototype._regenerateVertexData = function () {
  33951. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33952. };
  33953. BoxGeometry.prototype.copy = function (id) {
  33954. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33955. };
  33956. BoxGeometry.prototype.serialize = function () {
  33957. var serializationObject = _super.prototype.serialize.call(this);
  33958. serializationObject.size = this.size;
  33959. return serializationObject;
  33960. };
  33961. BoxGeometry.Parse = function (parsedBox, scene) {
  33962. if (scene.getGeometryByID(parsedBox.id)) {
  33963. return null; // null since geometry could be something else than a box...
  33964. }
  33965. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33966. if (BABYLON.Tags) {
  33967. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33968. }
  33969. scene.pushGeometry(box, true);
  33970. return box;
  33971. };
  33972. return BoxGeometry;
  33973. }(_PrimitiveGeometry));
  33974. BABYLON.BoxGeometry = BoxGeometry;
  33975. /**
  33976. * Creates a sphere geometry
  33977. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33978. */
  33979. var SphereGeometry = /** @class */ (function (_super) {
  33980. __extends(SphereGeometry, _super);
  33981. /**
  33982. * Create a new sphere geometry
  33983. * @param id defines the unique ID of the geometry
  33984. * @param scene defines the hosting scene
  33985. * @param segments defines the number of segments to use to create the sphere
  33986. * @param diameter defines the diameter of the sphere
  33987. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33988. * @param mesh defines the hosting mesh (can be null)
  33989. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33990. */
  33991. function SphereGeometry(id, scene,
  33992. /**
  33993. * Defines the number of segments to use to create the sphere
  33994. */
  33995. segments,
  33996. /**
  33997. * Defines the diameter of the sphere
  33998. */
  33999. diameter, canBeRegenerated, mesh,
  34000. /**
  34001. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34002. */
  34003. side) {
  34004. if (mesh === void 0) { mesh = null; }
  34005. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34006. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34007. _this.segments = segments;
  34008. _this.diameter = diameter;
  34009. _this.side = side;
  34010. return _this;
  34011. }
  34012. SphereGeometry.prototype._regenerateVertexData = function () {
  34013. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34014. };
  34015. SphereGeometry.prototype.copy = function (id) {
  34016. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34017. };
  34018. SphereGeometry.prototype.serialize = function () {
  34019. var serializationObject = _super.prototype.serialize.call(this);
  34020. serializationObject.segments = this.segments;
  34021. serializationObject.diameter = this.diameter;
  34022. return serializationObject;
  34023. };
  34024. SphereGeometry.Parse = function (parsedSphere, scene) {
  34025. if (scene.getGeometryByID(parsedSphere.id)) {
  34026. return null; // null since geometry could be something else than a sphere...
  34027. }
  34028. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34029. if (BABYLON.Tags) {
  34030. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34031. }
  34032. scene.pushGeometry(sphere, true);
  34033. return sphere;
  34034. };
  34035. return SphereGeometry;
  34036. }(_PrimitiveGeometry));
  34037. BABYLON.SphereGeometry = SphereGeometry;
  34038. /**
  34039. * Creates a disc geometry
  34040. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  34041. */
  34042. var DiscGeometry = /** @class */ (function (_super) {
  34043. __extends(DiscGeometry, _super);
  34044. /**
  34045. * Creates a new disc geometry
  34046. * @param id defines the unique ID of the geometry
  34047. * @param scene defines the hosting scene
  34048. * @param radius defines the radius of the disc
  34049. * @param tessellation defines the tesselation factor to apply to the disc
  34050. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34051. * @param mesh defines the hosting mesh (can be null)
  34052. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34053. */
  34054. function DiscGeometry(id, scene,
  34055. /**
  34056. * Defines the radius of the disc
  34057. */
  34058. radius,
  34059. /**
  34060. * Defines the tesselation factor to apply to the disc
  34061. */
  34062. tessellation, canBeRegenerated, mesh,
  34063. /**
  34064. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34065. */
  34066. side) {
  34067. if (mesh === void 0) { mesh = null; }
  34068. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34069. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34070. _this.radius = radius;
  34071. _this.tessellation = tessellation;
  34072. _this.side = side;
  34073. return _this;
  34074. }
  34075. DiscGeometry.prototype._regenerateVertexData = function () {
  34076. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34077. };
  34078. DiscGeometry.prototype.copy = function (id) {
  34079. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34080. };
  34081. return DiscGeometry;
  34082. }(_PrimitiveGeometry));
  34083. BABYLON.DiscGeometry = DiscGeometry;
  34084. /**
  34085. * Creates a new cylinder geometry
  34086. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  34087. */
  34088. var CylinderGeometry = /** @class */ (function (_super) {
  34089. __extends(CylinderGeometry, _super);
  34090. /**
  34091. * Creates a new cylinder geometry
  34092. * @param id defines the unique ID of the geometry
  34093. * @param scene defines the hosting scene
  34094. * @param height defines the height of the cylinder
  34095. * @param diameterTop defines the diameter of the cylinder's top cap
  34096. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  34097. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  34098. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  34099. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34100. * @param mesh defines the hosting mesh (can be null)
  34101. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34102. */
  34103. function CylinderGeometry(id, scene,
  34104. /**
  34105. * Defines the height of the cylinder
  34106. */
  34107. height,
  34108. /**
  34109. * Defines the diameter of the cylinder's top cap
  34110. */
  34111. diameterTop,
  34112. /**
  34113. * Defines the diameter of the cylinder's bottom cap
  34114. */
  34115. diameterBottom,
  34116. /**
  34117. * Defines the tessellation factor to apply to the cylinder
  34118. */
  34119. tessellation,
  34120. /**
  34121. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  34122. */
  34123. subdivisions, canBeRegenerated, mesh,
  34124. /**
  34125. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34126. */
  34127. side) {
  34128. if (subdivisions === void 0) { subdivisions = 1; }
  34129. if (mesh === void 0) { mesh = null; }
  34130. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34131. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34132. _this.height = height;
  34133. _this.diameterTop = diameterTop;
  34134. _this.diameterBottom = diameterBottom;
  34135. _this.tessellation = tessellation;
  34136. _this.subdivisions = subdivisions;
  34137. _this.side = side;
  34138. return _this;
  34139. }
  34140. CylinderGeometry.prototype._regenerateVertexData = function () {
  34141. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34142. };
  34143. CylinderGeometry.prototype.copy = function (id) {
  34144. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34145. };
  34146. CylinderGeometry.prototype.serialize = function () {
  34147. var serializationObject = _super.prototype.serialize.call(this);
  34148. serializationObject.height = this.height;
  34149. serializationObject.diameterTop = this.diameterTop;
  34150. serializationObject.diameterBottom = this.diameterBottom;
  34151. serializationObject.tessellation = this.tessellation;
  34152. return serializationObject;
  34153. };
  34154. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  34155. if (scene.getGeometryByID(parsedCylinder.id)) {
  34156. return null; // null since geometry could be something else than a cylinder...
  34157. }
  34158. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34159. if (BABYLON.Tags) {
  34160. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34161. }
  34162. scene.pushGeometry(cylinder, true);
  34163. return cylinder;
  34164. };
  34165. return CylinderGeometry;
  34166. }(_PrimitiveGeometry));
  34167. BABYLON.CylinderGeometry = CylinderGeometry;
  34168. /**
  34169. * Creates a new torus geometry
  34170. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  34171. */
  34172. var TorusGeometry = /** @class */ (function (_super) {
  34173. __extends(TorusGeometry, _super);
  34174. /**
  34175. * Creates a new torus geometry
  34176. * @param id defines the unique ID of the geometry
  34177. * @param scene defines the hosting scene
  34178. * @param diameter defines the diameter of the torus
  34179. * @param thickness defines the thickness of the torus (ie. internal diameter)
  34180. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  34181. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34182. * @param mesh defines the hosting mesh (can be null)
  34183. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34184. */
  34185. function TorusGeometry(id, scene,
  34186. /**
  34187. * Defines the diameter of the torus
  34188. */
  34189. diameter,
  34190. /**
  34191. * Defines the thickness of the torus (ie. internal diameter)
  34192. */
  34193. thickness,
  34194. /**
  34195. * Defines the tesselation factor to apply to the torus
  34196. */
  34197. tessellation, canBeRegenerated, mesh,
  34198. /**
  34199. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34200. */
  34201. side) {
  34202. if (mesh === void 0) { mesh = null; }
  34203. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34204. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34205. _this.diameter = diameter;
  34206. _this.thickness = thickness;
  34207. _this.tessellation = tessellation;
  34208. _this.side = side;
  34209. return _this;
  34210. }
  34211. TorusGeometry.prototype._regenerateVertexData = function () {
  34212. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34213. };
  34214. TorusGeometry.prototype.copy = function (id) {
  34215. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34216. };
  34217. TorusGeometry.prototype.serialize = function () {
  34218. var serializationObject = _super.prototype.serialize.call(this);
  34219. serializationObject.diameter = this.diameter;
  34220. serializationObject.thickness = this.thickness;
  34221. serializationObject.tessellation = this.tessellation;
  34222. return serializationObject;
  34223. };
  34224. TorusGeometry.Parse = function (parsedTorus, scene) {
  34225. if (scene.getGeometryByID(parsedTorus.id)) {
  34226. return null; // null since geometry could be something else than a torus...
  34227. }
  34228. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34229. if (BABYLON.Tags) {
  34230. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34231. }
  34232. scene.pushGeometry(torus, true);
  34233. return torus;
  34234. };
  34235. return TorusGeometry;
  34236. }(_PrimitiveGeometry));
  34237. BABYLON.TorusGeometry = TorusGeometry;
  34238. /**
  34239. * Creates a new ground geometry
  34240. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  34241. */
  34242. var GroundGeometry = /** @class */ (function (_super) {
  34243. __extends(GroundGeometry, _super);
  34244. /**
  34245. * Creates a new ground geometry
  34246. * @param id defines the unique ID of the geometry
  34247. * @param scene defines the hosting scene
  34248. * @param width defines the width of the ground
  34249. * @param height defines the height of the ground
  34250. * @param subdivisions defines the subdivisions to apply to the ground
  34251. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34252. * @param mesh defines the hosting mesh (can be null)
  34253. */
  34254. function GroundGeometry(id, scene,
  34255. /**
  34256. * Defines the width of the ground
  34257. */
  34258. width,
  34259. /**
  34260. * Defines the height of the ground
  34261. */
  34262. height,
  34263. /**
  34264. * Defines the subdivisions to apply to the ground
  34265. */
  34266. subdivisions, canBeRegenerated, mesh) {
  34267. if (mesh === void 0) { mesh = null; }
  34268. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34269. _this.width = width;
  34270. _this.height = height;
  34271. _this.subdivisions = subdivisions;
  34272. return _this;
  34273. }
  34274. GroundGeometry.prototype._regenerateVertexData = function () {
  34275. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34276. };
  34277. GroundGeometry.prototype.copy = function (id) {
  34278. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34279. };
  34280. GroundGeometry.prototype.serialize = function () {
  34281. var serializationObject = _super.prototype.serialize.call(this);
  34282. serializationObject.width = this.width;
  34283. serializationObject.height = this.height;
  34284. serializationObject.subdivisions = this.subdivisions;
  34285. return serializationObject;
  34286. };
  34287. GroundGeometry.Parse = function (parsedGround, scene) {
  34288. if (scene.getGeometryByID(parsedGround.id)) {
  34289. return null; // null since geometry could be something else than a ground...
  34290. }
  34291. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34292. if (BABYLON.Tags) {
  34293. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34294. }
  34295. scene.pushGeometry(ground, true);
  34296. return ground;
  34297. };
  34298. return GroundGeometry;
  34299. }(_PrimitiveGeometry));
  34300. BABYLON.GroundGeometry = GroundGeometry;
  34301. /**
  34302. * Creates a tiled ground geometry
  34303. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  34304. */
  34305. var TiledGroundGeometry = /** @class */ (function (_super) {
  34306. __extends(TiledGroundGeometry, _super);
  34307. /**
  34308. * Creates a tiled ground geometry
  34309. * @param id defines the unique ID of the geometry
  34310. * @param scene defines the hosting scene
  34311. * @param xmin defines the minimum value on X axis
  34312. * @param zmin defines the minimum value on Z axis
  34313. * @param xmax defines the maximum value on X axis
  34314. * @param zmax defines the maximum value on Z axis
  34315. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  34316. * @param precision defines the precision to use when computing the tiles
  34317. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34318. * @param mesh defines the hosting mesh (can be null)
  34319. */
  34320. function TiledGroundGeometry(id, scene,
  34321. /**
  34322. * Defines the minimum value on X axis
  34323. */
  34324. xmin,
  34325. /**
  34326. * Defines the minimum value on Z axis
  34327. */
  34328. zmin,
  34329. /**
  34330. * Defines the maximum value on X axis
  34331. */
  34332. xmax,
  34333. /**
  34334. * Defines the maximum value on Z axis
  34335. */
  34336. zmax,
  34337. /**
  34338. * Defines the subdivisions to apply to the ground
  34339. */
  34340. subdivisions,
  34341. /**
  34342. * Defines the precision to use when computing the tiles
  34343. */
  34344. precision, canBeRegenerated, mesh) {
  34345. if (mesh === void 0) { mesh = null; }
  34346. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34347. _this.xmin = xmin;
  34348. _this.zmin = zmin;
  34349. _this.xmax = xmax;
  34350. _this.zmax = zmax;
  34351. _this.subdivisions = subdivisions;
  34352. _this.precision = precision;
  34353. return _this;
  34354. }
  34355. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  34356. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34357. };
  34358. TiledGroundGeometry.prototype.copy = function (id) {
  34359. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34360. };
  34361. return TiledGroundGeometry;
  34362. }(_PrimitiveGeometry));
  34363. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  34364. /**
  34365. * Creates a plane geometry
  34366. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  34367. */
  34368. var PlaneGeometry = /** @class */ (function (_super) {
  34369. __extends(PlaneGeometry, _super);
  34370. /**
  34371. * Creates a plane geometry
  34372. * @param id defines the unique ID of the geometry
  34373. * @param scene defines the hosting scene
  34374. * @param size defines the size of the plane (width === height)
  34375. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34376. * @param mesh defines the hosting mesh (can be null)
  34377. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34378. */
  34379. function PlaneGeometry(id, scene,
  34380. /**
  34381. * Defines the size of the plane (width === height)
  34382. */
  34383. size, canBeRegenerated, mesh,
  34384. /**
  34385. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34386. */
  34387. side) {
  34388. if (mesh === void 0) { mesh = null; }
  34389. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34390. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34391. _this.size = size;
  34392. _this.side = side;
  34393. return _this;
  34394. }
  34395. PlaneGeometry.prototype._regenerateVertexData = function () {
  34396. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34397. };
  34398. PlaneGeometry.prototype.copy = function (id) {
  34399. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34400. };
  34401. PlaneGeometry.prototype.serialize = function () {
  34402. var serializationObject = _super.prototype.serialize.call(this);
  34403. serializationObject.size = this.size;
  34404. return serializationObject;
  34405. };
  34406. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34407. if (scene.getGeometryByID(parsedPlane.id)) {
  34408. return null; // null since geometry could be something else than a ground...
  34409. }
  34410. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34411. if (BABYLON.Tags) {
  34412. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34413. }
  34414. scene.pushGeometry(plane, true);
  34415. return plane;
  34416. };
  34417. return PlaneGeometry;
  34418. }(_PrimitiveGeometry));
  34419. BABYLON.PlaneGeometry = PlaneGeometry;
  34420. /**
  34421. * Creates a torus knot geometry
  34422. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34423. */
  34424. var TorusKnotGeometry = /** @class */ (function (_super) {
  34425. __extends(TorusKnotGeometry, _super);
  34426. /**
  34427. * Creates a torus knot geometry
  34428. * @param id defines the unique ID of the geometry
  34429. * @param scene defines the hosting scene
  34430. * @param radius defines the radius of the torus knot
  34431. * @param tube defines the thickness of the torus knot tube
  34432. * @param radialSegments defines the number of radial segments
  34433. * @param tubularSegments defines the number of tubular segments
  34434. * @param p defines the first number of windings
  34435. * @param q defines the second number of windings
  34436. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34437. * @param mesh defines the hosting mesh (can be null)
  34438. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34439. */
  34440. function TorusKnotGeometry(id, scene,
  34441. /**
  34442. * Defines the radius of the torus knot
  34443. */
  34444. radius,
  34445. /**
  34446. * Defines the thickness of the torus knot tube
  34447. */
  34448. tube,
  34449. /**
  34450. * Defines the number of radial segments
  34451. */
  34452. radialSegments,
  34453. /**
  34454. * Defines the number of tubular segments
  34455. */
  34456. tubularSegments,
  34457. /**
  34458. * Defines the first number of windings
  34459. */
  34460. p,
  34461. /**
  34462. * Defines the second number of windings
  34463. */
  34464. q, canBeRegenerated, mesh,
  34465. /**
  34466. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34467. */
  34468. side) {
  34469. if (mesh === void 0) { mesh = null; }
  34470. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34471. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34472. _this.radius = radius;
  34473. _this.tube = tube;
  34474. _this.radialSegments = radialSegments;
  34475. _this.tubularSegments = tubularSegments;
  34476. _this.p = p;
  34477. _this.q = q;
  34478. _this.side = side;
  34479. return _this;
  34480. }
  34481. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34482. 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 });
  34483. };
  34484. TorusKnotGeometry.prototype.copy = function (id) {
  34485. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34486. };
  34487. TorusKnotGeometry.prototype.serialize = function () {
  34488. var serializationObject = _super.prototype.serialize.call(this);
  34489. serializationObject.radius = this.radius;
  34490. serializationObject.tube = this.tube;
  34491. serializationObject.radialSegments = this.radialSegments;
  34492. serializationObject.tubularSegments = this.tubularSegments;
  34493. serializationObject.p = this.p;
  34494. serializationObject.q = this.q;
  34495. return serializationObject;
  34496. };
  34497. ;
  34498. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34499. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34500. return null; // null since geometry could be something else than a ground...
  34501. }
  34502. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34503. if (BABYLON.Tags) {
  34504. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34505. }
  34506. scene.pushGeometry(torusKnot, true);
  34507. return torusKnot;
  34508. };
  34509. return TorusKnotGeometry;
  34510. }(_PrimitiveGeometry));
  34511. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34512. //}
  34513. })(BABYLON || (BABYLON = {}));
  34514. //# sourceMappingURL=babylon.geometry.js.map
  34515. var BABYLON;
  34516. (function (BABYLON) {
  34517. var PostProcessManager = /** @class */ (function () {
  34518. function PostProcessManager(scene) {
  34519. this._vertexBuffers = {};
  34520. this._scene = scene;
  34521. }
  34522. PostProcessManager.prototype._prepareBuffers = function () {
  34523. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34524. return;
  34525. }
  34526. // VBO
  34527. var vertices = [];
  34528. vertices.push(1, 1);
  34529. vertices.push(-1, 1);
  34530. vertices.push(-1, -1);
  34531. vertices.push(1, -1);
  34532. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34533. this._buildIndexBuffer();
  34534. };
  34535. PostProcessManager.prototype._buildIndexBuffer = function () {
  34536. // Indices
  34537. var indices = [];
  34538. indices.push(0);
  34539. indices.push(1);
  34540. indices.push(2);
  34541. indices.push(0);
  34542. indices.push(2);
  34543. indices.push(3);
  34544. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34545. };
  34546. PostProcessManager.prototype._rebuild = function () {
  34547. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34548. if (!vb) {
  34549. return;
  34550. }
  34551. vb._rebuild();
  34552. this._buildIndexBuffer();
  34553. };
  34554. // Methods
  34555. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34556. if (sourceTexture === void 0) { sourceTexture = null; }
  34557. if (postProcesses === void 0) { postProcesses = null; }
  34558. var camera = this._scene.activeCamera;
  34559. if (!camera) {
  34560. return false;
  34561. }
  34562. var postProcesses = postProcesses || camera._postProcesses;
  34563. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34564. return false;
  34565. }
  34566. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34567. return true;
  34568. };
  34569. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34570. if (targetTexture === void 0) { targetTexture = null; }
  34571. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34572. var engine = this._scene.getEngine();
  34573. for (var index = 0; index < postProcesses.length; index++) {
  34574. if (index < postProcesses.length - 1) {
  34575. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34576. }
  34577. else {
  34578. if (targetTexture) {
  34579. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34580. }
  34581. else {
  34582. engine.restoreDefaultFramebuffer();
  34583. }
  34584. }
  34585. var pp = postProcesses[index];
  34586. var effect = pp.apply();
  34587. if (effect) {
  34588. pp.onBeforeRenderObservable.notifyObservers(effect);
  34589. // VBOs
  34590. this._prepareBuffers();
  34591. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34592. // Draw order
  34593. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34594. pp.onAfterRenderObservable.notifyObservers(effect);
  34595. }
  34596. }
  34597. // Restore depth buffer
  34598. engine.setDepthBuffer(true);
  34599. engine.setDepthWrite(true);
  34600. };
  34601. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34602. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34603. var camera = this._scene.activeCamera;
  34604. if (!camera) {
  34605. return;
  34606. }
  34607. postProcesses = postProcesses || camera._postProcesses;
  34608. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34609. return;
  34610. }
  34611. var engine = this._scene.getEngine();
  34612. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34613. if (index < len - 1) {
  34614. postProcesses[index + 1].activate(camera, targetTexture);
  34615. }
  34616. else {
  34617. if (targetTexture) {
  34618. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34619. }
  34620. else {
  34621. engine.restoreDefaultFramebuffer();
  34622. }
  34623. }
  34624. if (doNotPresent) {
  34625. break;
  34626. }
  34627. var pp = postProcesses[index];
  34628. var effect = pp.apply();
  34629. if (effect) {
  34630. pp.onBeforeRenderObservable.notifyObservers(effect);
  34631. // VBOs
  34632. this._prepareBuffers();
  34633. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34634. // Draw order
  34635. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34636. pp.onAfterRenderObservable.notifyObservers(effect);
  34637. }
  34638. }
  34639. // Restore states
  34640. engine.setDepthBuffer(true);
  34641. engine.setDepthWrite(true);
  34642. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34643. };
  34644. PostProcessManager.prototype.dispose = function () {
  34645. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34646. if (buffer) {
  34647. buffer.dispose();
  34648. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34649. }
  34650. if (this._indexBuffer) {
  34651. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34652. this._indexBuffer = null;
  34653. }
  34654. };
  34655. return PostProcessManager;
  34656. }());
  34657. BABYLON.PostProcessManager = PostProcessManager;
  34658. })(BABYLON || (BABYLON = {}));
  34659. //# sourceMappingURL=babylon.postProcessManager.js.map
  34660. var BABYLON;
  34661. (function (BABYLON) {
  34662. /**
  34663. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34664. */
  34665. var PerformanceMonitor = /** @class */ (function () {
  34666. /**
  34667. * constructor
  34668. * @param frameSampleSize The number of samples required to saturate the sliding window
  34669. */
  34670. function PerformanceMonitor(frameSampleSize) {
  34671. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34672. this._enabled = true;
  34673. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34674. }
  34675. /**
  34676. * Samples current frame
  34677. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34678. */
  34679. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34680. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34681. if (!this._enabled)
  34682. return;
  34683. if (this._lastFrameTimeMs != null) {
  34684. var dt = timeMs - this._lastFrameTimeMs;
  34685. this._rollingFrameTime.add(dt);
  34686. }
  34687. this._lastFrameTimeMs = timeMs;
  34688. };
  34689. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34690. /**
  34691. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34692. * @return Average frame time in milliseconds
  34693. */
  34694. get: function () {
  34695. return this._rollingFrameTime.average;
  34696. },
  34697. enumerable: true,
  34698. configurable: true
  34699. });
  34700. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34701. /**
  34702. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34703. * @return Frame time variance in milliseconds squared
  34704. */
  34705. get: function () {
  34706. return this._rollingFrameTime.variance;
  34707. },
  34708. enumerable: true,
  34709. configurable: true
  34710. });
  34711. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34712. /**
  34713. * Returns the frame time of the most recent frame
  34714. * @return Frame time in milliseconds
  34715. */
  34716. get: function () {
  34717. return this._rollingFrameTime.history(0);
  34718. },
  34719. enumerable: true,
  34720. configurable: true
  34721. });
  34722. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34723. /**
  34724. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34725. * @return Framerate in frames per second
  34726. */
  34727. get: function () {
  34728. return 1000.0 / this._rollingFrameTime.average;
  34729. },
  34730. enumerable: true,
  34731. configurable: true
  34732. });
  34733. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34734. /**
  34735. * Returns the average framerate in frames per second using the most recent frame time
  34736. * @return Framerate in frames per second
  34737. */
  34738. get: function () {
  34739. var history = this._rollingFrameTime.history(0);
  34740. if (history === 0) {
  34741. return 0;
  34742. }
  34743. return 1000.0 / history;
  34744. },
  34745. enumerable: true,
  34746. configurable: true
  34747. });
  34748. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34749. /**
  34750. * Returns true if enough samples have been taken to completely fill the sliding window
  34751. * @return true if saturated
  34752. */
  34753. get: function () {
  34754. return this._rollingFrameTime.isSaturated();
  34755. },
  34756. enumerable: true,
  34757. configurable: true
  34758. });
  34759. /**
  34760. * Enables contributions to the sliding window sample set
  34761. */
  34762. PerformanceMonitor.prototype.enable = function () {
  34763. this._enabled = true;
  34764. };
  34765. /**
  34766. * Disables contributions to the sliding window sample set
  34767. * Samples will not be interpolated over the disabled period
  34768. */
  34769. PerformanceMonitor.prototype.disable = function () {
  34770. this._enabled = false;
  34771. //clear last sample to avoid interpolating over the disabled period when next enabled
  34772. this._lastFrameTimeMs = null;
  34773. };
  34774. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34775. /**
  34776. * Returns true if sampling is enabled
  34777. * @return true if enabled
  34778. */
  34779. get: function () {
  34780. return this._enabled;
  34781. },
  34782. enumerable: true,
  34783. configurable: true
  34784. });
  34785. /**
  34786. * Resets performance monitor
  34787. */
  34788. PerformanceMonitor.prototype.reset = function () {
  34789. //clear last sample to avoid interpolating over the disabled period when next enabled
  34790. this._lastFrameTimeMs = null;
  34791. //wipe record
  34792. this._rollingFrameTime.reset();
  34793. };
  34794. return PerformanceMonitor;
  34795. }());
  34796. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34797. /**
  34798. * RollingAverage
  34799. *
  34800. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34801. */
  34802. var RollingAverage = /** @class */ (function () {
  34803. /**
  34804. * constructor
  34805. * @param length The number of samples required to saturate the sliding window
  34806. */
  34807. function RollingAverage(length) {
  34808. this._samples = new Array(length);
  34809. this.reset();
  34810. }
  34811. /**
  34812. * Adds a sample to the sample set
  34813. * @param v The sample value
  34814. */
  34815. RollingAverage.prototype.add = function (v) {
  34816. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34817. var delta;
  34818. //we need to check if we've already wrapped round
  34819. if (this.isSaturated()) {
  34820. //remove bottom of stack from mean
  34821. var bottomValue = this._samples[this._pos];
  34822. delta = bottomValue - this.average;
  34823. this.average -= delta / (this._sampleCount - 1);
  34824. this._m2 -= delta * (bottomValue - this.average);
  34825. }
  34826. else {
  34827. this._sampleCount++;
  34828. }
  34829. //add new value to mean
  34830. delta = v - this.average;
  34831. this.average += delta / (this._sampleCount);
  34832. this._m2 += delta * (v - this.average);
  34833. //set the new variance
  34834. this.variance = this._m2 / (this._sampleCount - 1);
  34835. this._samples[this._pos] = v;
  34836. this._pos++;
  34837. this._pos %= this._samples.length; //positive wrap around
  34838. };
  34839. /**
  34840. * Returns previously added values or null if outside of history or outside the sliding window domain
  34841. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34842. * @return Value previously recorded with add() or null if outside of range
  34843. */
  34844. RollingAverage.prototype.history = function (i) {
  34845. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34846. return 0;
  34847. }
  34848. var i0 = this._wrapPosition(this._pos - 1.0);
  34849. return this._samples[this._wrapPosition(i0 - i)];
  34850. };
  34851. /**
  34852. * Returns true if enough samples have been taken to completely fill the sliding window
  34853. * @return true if sample-set saturated
  34854. */
  34855. RollingAverage.prototype.isSaturated = function () {
  34856. return this._sampleCount >= this._samples.length;
  34857. };
  34858. /**
  34859. * Resets the rolling average (equivalent to 0 samples taken so far)
  34860. */
  34861. RollingAverage.prototype.reset = function () {
  34862. this.average = 0;
  34863. this.variance = 0;
  34864. this._sampleCount = 0;
  34865. this._pos = 0;
  34866. this._m2 = 0;
  34867. };
  34868. /**
  34869. * Wraps a value around the sample range boundaries
  34870. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34871. * @return Wrapped position in sample range
  34872. */
  34873. RollingAverage.prototype._wrapPosition = function (i) {
  34874. var max = this._samples.length;
  34875. return ((i % max) + max) % max;
  34876. };
  34877. return RollingAverage;
  34878. }());
  34879. BABYLON.RollingAverage = RollingAverage;
  34880. })(BABYLON || (BABYLON = {}));
  34881. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34882. var BABYLON;
  34883. (function (BABYLON) {
  34884. /**
  34885. * This groups together the common properties used for image processing either in direct forward pass
  34886. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34887. * or not.
  34888. */
  34889. var ImageProcessingConfiguration = /** @class */ (function () {
  34890. function ImageProcessingConfiguration() {
  34891. /**
  34892. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34893. */
  34894. this.colorCurves = new BABYLON.ColorCurves();
  34895. this._colorCurvesEnabled = false;
  34896. this._colorGradingEnabled = false;
  34897. this._colorGradingWithGreenDepth = true;
  34898. this._colorGradingBGR = true;
  34899. this._exposure = 1.0;
  34900. this._toneMappingEnabled = false;
  34901. this._contrast = 1.0;
  34902. /**
  34903. * Vignette stretch size.
  34904. */
  34905. this.vignetteStretch = 0;
  34906. /**
  34907. * Vignette centre X Offset.
  34908. */
  34909. this.vignetteCentreX = 0;
  34910. /**
  34911. * Vignette centre Y Offset.
  34912. */
  34913. this.vignetteCentreY = 0;
  34914. /**
  34915. * Vignette weight or intensity of the vignette effect.
  34916. */
  34917. this.vignetteWeight = 1.5;
  34918. /**
  34919. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34920. * if vignetteEnabled is set to true.
  34921. */
  34922. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34923. /**
  34924. * Camera field of view used by the Vignette effect.
  34925. */
  34926. this.vignetteCameraFov = 0.5;
  34927. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34928. this._vignetteEnabled = false;
  34929. this._applyByPostProcess = false;
  34930. this._isEnabled = true;
  34931. /**
  34932. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34933. * @type {BABYLON.Observable}
  34934. */
  34935. this.onUpdateParameters = new BABYLON.Observable();
  34936. }
  34937. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34938. /**
  34939. * Gets wether the color curves effect is enabled.
  34940. */
  34941. get: function () {
  34942. return this._colorCurvesEnabled;
  34943. },
  34944. /**
  34945. * Sets wether the color curves effect is enabled.
  34946. */
  34947. set: function (value) {
  34948. if (this._colorCurvesEnabled === value) {
  34949. return;
  34950. }
  34951. this._colorCurvesEnabled = value;
  34952. this._updateParameters();
  34953. },
  34954. enumerable: true,
  34955. configurable: true
  34956. });
  34957. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34958. /**
  34959. * Gets wether the color grading effect is enabled.
  34960. */
  34961. get: function () {
  34962. return this._colorGradingEnabled;
  34963. },
  34964. /**
  34965. * Sets wether the color grading effect is enabled.
  34966. */
  34967. set: function (value) {
  34968. if (this._colorGradingEnabled === value) {
  34969. return;
  34970. }
  34971. this._colorGradingEnabled = value;
  34972. this._updateParameters();
  34973. },
  34974. enumerable: true,
  34975. configurable: true
  34976. });
  34977. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34978. /**
  34979. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34980. */
  34981. get: function () {
  34982. return this._colorGradingWithGreenDepth;
  34983. },
  34984. /**
  34985. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34986. */
  34987. set: function (value) {
  34988. if (this._colorGradingWithGreenDepth === value) {
  34989. return;
  34990. }
  34991. this._colorGradingWithGreenDepth = value;
  34992. this._updateParameters();
  34993. },
  34994. enumerable: true,
  34995. configurable: true
  34996. });
  34997. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34998. /**
  34999. * Gets wether the color grading texture contains BGR values.
  35000. */
  35001. get: function () {
  35002. return this._colorGradingBGR;
  35003. },
  35004. /**
  35005. * Sets wether the color grading texture contains BGR values.
  35006. */
  35007. set: function (value) {
  35008. if (this._colorGradingBGR === value) {
  35009. return;
  35010. }
  35011. this._colorGradingBGR = value;
  35012. this._updateParameters();
  35013. },
  35014. enumerable: true,
  35015. configurable: true
  35016. });
  35017. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  35018. /**
  35019. * Gets the Exposure used in the effect.
  35020. */
  35021. get: function () {
  35022. return this._exposure;
  35023. },
  35024. /**
  35025. * Sets the Exposure used in the effect.
  35026. */
  35027. set: function (value) {
  35028. if (this._exposure === value) {
  35029. return;
  35030. }
  35031. this._exposure = value;
  35032. this._updateParameters();
  35033. },
  35034. enumerable: true,
  35035. configurable: true
  35036. });
  35037. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  35038. /**
  35039. * Gets wether the tone mapping effect is enabled.
  35040. */
  35041. get: function () {
  35042. return this._toneMappingEnabled;
  35043. },
  35044. /**
  35045. * Sets wether the tone mapping effect is enabled.
  35046. */
  35047. set: function (value) {
  35048. if (this._toneMappingEnabled === value) {
  35049. return;
  35050. }
  35051. this._toneMappingEnabled = value;
  35052. this._updateParameters();
  35053. },
  35054. enumerable: true,
  35055. configurable: true
  35056. });
  35057. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  35058. /**
  35059. * Gets the contrast used in the effect.
  35060. */
  35061. get: function () {
  35062. return this._contrast;
  35063. },
  35064. /**
  35065. * Sets the contrast used in the effect.
  35066. */
  35067. set: function (value) {
  35068. if (this._contrast === value) {
  35069. return;
  35070. }
  35071. this._contrast = value;
  35072. this._updateParameters();
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  35078. /**
  35079. * Gets the vignette blend mode allowing different kind of effect.
  35080. */
  35081. get: function () {
  35082. return this._vignetteBlendMode;
  35083. },
  35084. /**
  35085. * Sets the vignette blend mode allowing different kind of effect.
  35086. */
  35087. set: function (value) {
  35088. if (this._vignetteBlendMode === value) {
  35089. return;
  35090. }
  35091. this._vignetteBlendMode = value;
  35092. this._updateParameters();
  35093. },
  35094. enumerable: true,
  35095. configurable: true
  35096. });
  35097. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  35098. /**
  35099. * Gets wether the vignette effect is enabled.
  35100. */
  35101. get: function () {
  35102. return this._vignetteEnabled;
  35103. },
  35104. /**
  35105. * Sets wether the vignette effect is enabled.
  35106. */
  35107. set: function (value) {
  35108. if (this._vignetteEnabled === value) {
  35109. return;
  35110. }
  35111. this._vignetteEnabled = value;
  35112. this._updateParameters();
  35113. },
  35114. enumerable: true,
  35115. configurable: true
  35116. });
  35117. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  35118. /**
  35119. * Gets wether the image processing is applied through a post process or not.
  35120. */
  35121. get: function () {
  35122. return this._applyByPostProcess;
  35123. },
  35124. /**
  35125. * Sets wether the image processing is applied through a post process or not.
  35126. */
  35127. set: function (value) {
  35128. if (this._applyByPostProcess === value) {
  35129. return;
  35130. }
  35131. this._applyByPostProcess = value;
  35132. this._updateParameters();
  35133. },
  35134. enumerable: true,
  35135. configurable: true
  35136. });
  35137. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  35138. /**
  35139. * Gets wether the image processing is enabled or not.
  35140. */
  35141. get: function () {
  35142. return this._isEnabled;
  35143. },
  35144. /**
  35145. * Sets wether the image processing is enabled or not.
  35146. */
  35147. set: function (value) {
  35148. if (this._isEnabled === value) {
  35149. return;
  35150. }
  35151. this._isEnabled = value;
  35152. this._updateParameters();
  35153. },
  35154. enumerable: true,
  35155. configurable: true
  35156. });
  35157. /**
  35158. * Method called each time the image processing information changes requires to recompile the effect.
  35159. */
  35160. ImageProcessingConfiguration.prototype._updateParameters = function () {
  35161. this.onUpdateParameters.notifyObservers(this);
  35162. };
  35163. ImageProcessingConfiguration.prototype.getClassName = function () {
  35164. return "ImageProcessingConfiguration";
  35165. };
  35166. /**
  35167. * Prepare the list of uniforms associated with the Image Processing effects.
  35168. * @param uniformsList The list of uniforms used in the effect
  35169. * @param defines the list of defines currently in use
  35170. */
  35171. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  35172. if (defines.EXPOSURE) {
  35173. uniforms.push("exposureLinear");
  35174. }
  35175. if (defines.CONTRAST) {
  35176. uniforms.push("contrast");
  35177. }
  35178. if (defines.COLORGRADING) {
  35179. uniforms.push("colorTransformSettings");
  35180. }
  35181. if (defines.VIGNETTE) {
  35182. uniforms.push("vInverseScreenSize");
  35183. uniforms.push("vignetteSettings1");
  35184. uniforms.push("vignetteSettings2");
  35185. }
  35186. if (defines.COLORCURVES) {
  35187. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35188. }
  35189. };
  35190. /**
  35191. * Prepare the list of samplers associated with the Image Processing effects.
  35192. * @param uniformsList The list of uniforms used in the effect
  35193. * @param defines the list of defines currently in use
  35194. */
  35195. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  35196. if (defines.COLORGRADING) {
  35197. samplersList.push("txColorTransform");
  35198. }
  35199. };
  35200. /**
  35201. * Prepare the list of defines associated to the shader.
  35202. * @param defines the list of defines to complete
  35203. */
  35204. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  35205. if (forPostProcess === void 0) { forPostProcess = false; }
  35206. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  35207. defines.VIGNETTE = false;
  35208. defines.TONEMAPPING = false;
  35209. defines.CONTRAST = false;
  35210. defines.EXPOSURE = false;
  35211. defines.COLORCURVES = false;
  35212. defines.COLORGRADING = false;
  35213. defines.COLORGRADING3D = false;
  35214. defines.IMAGEPROCESSING = false;
  35215. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  35216. return;
  35217. }
  35218. defines.VIGNETTE = this.vignetteEnabled;
  35219. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  35220. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  35221. defines.TONEMAPPING = this.toneMappingEnabled;
  35222. defines.CONTRAST = (this.contrast !== 1.0);
  35223. defines.EXPOSURE = (this.exposure !== 1.0);
  35224. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  35225. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  35226. if (defines.COLORGRADING) {
  35227. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  35228. }
  35229. else {
  35230. defines.COLORGRADING3D = false;
  35231. }
  35232. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  35233. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  35234. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  35235. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  35236. };
  35237. /**
  35238. * Returns true if all the image processing information are ready.
  35239. */
  35240. ImageProcessingConfiguration.prototype.isReady = function () {
  35241. // Color Grading texure can not be none blocking.
  35242. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  35243. };
  35244. /**
  35245. * Binds the image processing to the shader.
  35246. * @param effect The effect to bind to
  35247. */
  35248. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  35249. if (aspectRatio === void 0) { aspectRatio = 1; }
  35250. // Color Curves
  35251. if (this._colorCurvesEnabled && this.colorCurves) {
  35252. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  35253. }
  35254. // Vignette
  35255. if (this._vignetteEnabled) {
  35256. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  35257. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  35258. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  35259. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  35260. var vignetteScaleX = vignetteScaleY * aspectRatio;
  35261. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  35262. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  35263. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  35264. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  35265. var vignettePower = -2.0 * this.vignetteWeight;
  35266. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  35267. }
  35268. // Exposure
  35269. effect.setFloat("exposureLinear", this.exposure);
  35270. // Contrast
  35271. effect.setFloat("contrast", this.contrast);
  35272. // Color transform settings
  35273. if (this.colorGradingTexture) {
  35274. effect.setTexture("txColorTransform", this.colorGradingTexture);
  35275. var textureSize = this.colorGradingTexture.getSize().height;
  35276. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  35277. 0.5 / textureSize, // textureOffset
  35278. textureSize, // textureSize
  35279. this.colorGradingTexture.level // weight
  35280. );
  35281. }
  35282. };
  35283. /**
  35284. * Clones the current image processing instance.
  35285. * @return The cloned image processing
  35286. */
  35287. ImageProcessingConfiguration.prototype.clone = function () {
  35288. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  35289. };
  35290. /**
  35291. * Serializes the current image processing instance to a json representation.
  35292. * @return a JSON representation
  35293. */
  35294. ImageProcessingConfiguration.prototype.serialize = function () {
  35295. return BABYLON.SerializationHelper.Serialize(this);
  35296. };
  35297. /**
  35298. * Parses the image processing from a json representation.
  35299. * @param source the JSON source to parse
  35300. * @return The parsed image processing
  35301. */
  35302. ImageProcessingConfiguration.Parse = function (source) {
  35303. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  35304. };
  35305. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  35306. /**
  35307. * Used to apply the vignette as a mix with the pixel color.
  35308. */
  35309. get: function () {
  35310. return this._VIGNETTEMODE_MULTIPLY;
  35311. },
  35312. enumerable: true,
  35313. configurable: true
  35314. });
  35315. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  35316. /**
  35317. * Used to apply the vignette as a replacement of the pixel color.
  35318. */
  35319. get: function () {
  35320. return this._VIGNETTEMODE_OPAQUE;
  35321. },
  35322. enumerable: true,
  35323. configurable: true
  35324. });
  35325. // Static constants associated to the image processing.
  35326. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  35327. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  35328. __decorate([
  35329. BABYLON.serializeAsColorCurves()
  35330. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  35331. __decorate([
  35332. BABYLON.serialize()
  35333. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  35334. __decorate([
  35335. BABYLON.serializeAsTexture()
  35336. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  35337. __decorate([
  35338. BABYLON.serialize()
  35339. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  35340. __decorate([
  35341. BABYLON.serialize()
  35342. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  35343. __decorate([
  35344. BABYLON.serialize()
  35345. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  35346. __decorate([
  35347. BABYLON.serialize()
  35348. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  35349. __decorate([
  35350. BABYLON.serialize()
  35351. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  35352. __decorate([
  35353. BABYLON.serialize()
  35354. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  35355. __decorate([
  35356. BABYLON.serialize()
  35357. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  35358. __decorate([
  35359. BABYLON.serialize()
  35360. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  35361. __decorate([
  35362. BABYLON.serialize()
  35363. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  35364. __decorate([
  35365. BABYLON.serialize()
  35366. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  35367. __decorate([
  35368. BABYLON.serializeAsColor4()
  35369. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  35370. __decorate([
  35371. BABYLON.serialize()
  35372. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  35373. __decorate([
  35374. BABYLON.serialize()
  35375. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  35376. __decorate([
  35377. BABYLON.serialize()
  35378. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  35379. __decorate([
  35380. BABYLON.serialize()
  35381. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  35382. __decorate([
  35383. BABYLON.serialize()
  35384. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  35385. return ImageProcessingConfiguration;
  35386. }());
  35387. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35388. })(BABYLON || (BABYLON = {}));
  35389. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35390. var BABYLON;
  35391. (function (BABYLON) {
  35392. /**
  35393. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35394. * It can help converting any input color in a desired output one. This can then be used to create effects
  35395. * from sepia, black and white to sixties or futuristic rendering...
  35396. *
  35397. * The only supported format is currently 3dl.
  35398. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35399. */
  35400. var ColorGradingTexture = /** @class */ (function (_super) {
  35401. __extends(ColorGradingTexture, _super);
  35402. /**
  35403. * Instantiates a ColorGradingTexture from the following parameters.
  35404. *
  35405. * @param url The location of the color gradind data (currently only supporting 3dl)
  35406. * @param scene The scene the texture will be used in
  35407. */
  35408. function ColorGradingTexture(url, scene) {
  35409. var _this = _super.call(this, scene) || this;
  35410. if (!url) {
  35411. return _this;
  35412. }
  35413. _this._engine = scene.getEngine();
  35414. _this._textureMatrix = BABYLON.Matrix.Identity();
  35415. _this.name = url;
  35416. _this.url = url;
  35417. _this.hasAlpha = false;
  35418. _this.isCube = false;
  35419. _this.is3D = _this._engine.webGLVersion > 1;
  35420. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35421. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35422. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35423. _this.anisotropicFilteringLevel = 1;
  35424. _this._texture = _this._getFromCache(url, true);
  35425. if (!_this._texture) {
  35426. if (!scene.useDelayedTextureLoading) {
  35427. _this.loadTexture();
  35428. }
  35429. else {
  35430. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35431. }
  35432. }
  35433. return _this;
  35434. }
  35435. /**
  35436. * Returns the texture matrix used in most of the material.
  35437. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35438. */
  35439. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35440. return this._textureMatrix;
  35441. };
  35442. /**
  35443. * Occurs when the file being loaded is a .3dl LUT file.
  35444. */
  35445. ColorGradingTexture.prototype.load3dlTexture = function () {
  35446. var engine = this._engine;
  35447. var texture;
  35448. if (engine.webGLVersion === 1) {
  35449. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35450. }
  35451. else {
  35452. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35453. }
  35454. this._texture = texture;
  35455. var callback = function (text) {
  35456. if (typeof text !== "string") {
  35457. return;
  35458. }
  35459. var data = null;
  35460. var tempData = null;
  35461. var line;
  35462. var lines = text.split('\n');
  35463. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35464. var maxColor = 0;
  35465. for (var i = 0; i < lines.length; i++) {
  35466. line = lines[i];
  35467. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35468. continue;
  35469. if (line.indexOf('#') === 0)
  35470. continue;
  35471. var words = line.split(" ");
  35472. if (size === 0) {
  35473. // Number of space + one
  35474. size = words.length;
  35475. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35476. tempData = new Float32Array(size * size * size * 4);
  35477. continue;
  35478. }
  35479. if (size != 0) {
  35480. var r = Math.max(parseInt(words[0]), 0);
  35481. var g = Math.max(parseInt(words[1]), 0);
  35482. var b = Math.max(parseInt(words[2]), 0);
  35483. maxColor = Math.max(r, maxColor);
  35484. maxColor = Math.max(g, maxColor);
  35485. maxColor = Math.max(b, maxColor);
  35486. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35487. if (tempData) {
  35488. tempData[pixelStorageIndex + 0] = r;
  35489. tempData[pixelStorageIndex + 1] = g;
  35490. tempData[pixelStorageIndex + 2] = b;
  35491. }
  35492. pixelIndexSlice++;
  35493. if (pixelIndexSlice % size == 0) {
  35494. pixelIndexH++;
  35495. pixelIndexSlice = 0;
  35496. if (pixelIndexH % size == 0) {
  35497. pixelIndexW++;
  35498. pixelIndexH = 0;
  35499. }
  35500. }
  35501. }
  35502. }
  35503. if (tempData && data) {
  35504. for (var i = 0; i < tempData.length; i++) {
  35505. if (i > 0 && (i + 1) % 4 === 0) {
  35506. data[i] = 255;
  35507. }
  35508. else {
  35509. var value = tempData[i];
  35510. data[i] = (value / maxColor * 255);
  35511. }
  35512. }
  35513. }
  35514. if (texture.is3D) {
  35515. texture.updateSize(size, size, size);
  35516. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35517. }
  35518. else {
  35519. texture.updateSize(size * size, size);
  35520. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35521. }
  35522. };
  35523. var scene = this.getScene();
  35524. if (scene) {
  35525. scene._loadFile(this.url, callback);
  35526. }
  35527. else {
  35528. this._engine._loadFile(this.url, callback);
  35529. }
  35530. return this._texture;
  35531. };
  35532. /**
  35533. * Starts the loading process of the texture.
  35534. */
  35535. ColorGradingTexture.prototype.loadTexture = function () {
  35536. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35537. this.load3dlTexture();
  35538. }
  35539. };
  35540. /**
  35541. * Clones the color gradind texture.
  35542. */
  35543. ColorGradingTexture.prototype.clone = function () {
  35544. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35545. // Base texture
  35546. newTexture.level = this.level;
  35547. return newTexture;
  35548. };
  35549. /**
  35550. * Called during delayed load for textures.
  35551. */
  35552. ColorGradingTexture.prototype.delayLoad = function () {
  35553. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35554. return;
  35555. }
  35556. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35557. this._texture = this._getFromCache(this.url, true);
  35558. if (!this._texture) {
  35559. this.loadTexture();
  35560. }
  35561. };
  35562. /**
  35563. * Parses a color grading texture serialized by Babylon.
  35564. * @param parsedTexture The texture information being parsedTexture
  35565. * @param scene The scene to load the texture in
  35566. * @param rootUrl The root url of the data assets to load
  35567. * @return A color gradind texture
  35568. */
  35569. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35570. var texture = null;
  35571. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35572. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35573. texture.name = parsedTexture.name;
  35574. texture.level = parsedTexture.level;
  35575. }
  35576. return texture;
  35577. };
  35578. /**
  35579. * Serializes the LUT texture to json format.
  35580. */
  35581. ColorGradingTexture.prototype.serialize = function () {
  35582. if (!this.name) {
  35583. return null;
  35584. }
  35585. var serializationObject = {};
  35586. serializationObject.name = this.name;
  35587. serializationObject.level = this.level;
  35588. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35589. return serializationObject;
  35590. };
  35591. /**
  35592. * Empty line regex stored for GC.
  35593. */
  35594. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35595. return ColorGradingTexture;
  35596. }(BABYLON.BaseTexture));
  35597. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35598. })(BABYLON || (BABYLON = {}));
  35599. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35600. var BABYLON;
  35601. (function (BABYLON) {
  35602. /**
  35603. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35604. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35605. * 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;
  35606. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35607. */
  35608. var ColorCurves = /** @class */ (function () {
  35609. function ColorCurves() {
  35610. this._dirty = true;
  35611. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35612. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35613. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35614. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35615. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35616. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35617. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35618. this._globalHue = 30;
  35619. this._globalDensity = 0;
  35620. this._globalSaturation = 0;
  35621. this._globalExposure = 0;
  35622. this._highlightsHue = 30;
  35623. this._highlightsDensity = 0;
  35624. this._highlightsSaturation = 0;
  35625. this._highlightsExposure = 0;
  35626. this._midtonesHue = 30;
  35627. this._midtonesDensity = 0;
  35628. this._midtonesSaturation = 0;
  35629. this._midtonesExposure = 0;
  35630. this._shadowsHue = 30;
  35631. this._shadowsDensity = 0;
  35632. this._shadowsSaturation = 0;
  35633. this._shadowsExposure = 0;
  35634. }
  35635. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35636. /**
  35637. * Gets the global Hue value.
  35638. * 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).
  35639. */
  35640. get: function () {
  35641. return this._globalHue;
  35642. },
  35643. /**
  35644. * Sets the global Hue value.
  35645. * 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).
  35646. */
  35647. set: function (value) {
  35648. this._globalHue = value;
  35649. this._dirty = true;
  35650. },
  35651. enumerable: true,
  35652. configurable: true
  35653. });
  35654. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35655. /**
  35656. * Gets the global Density value.
  35657. * 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.
  35658. * Values less than zero provide a filter of opposite hue.
  35659. */
  35660. get: function () {
  35661. return this._globalDensity;
  35662. },
  35663. /**
  35664. * Sets the global Density value.
  35665. * 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.
  35666. * Values less than zero provide a filter of opposite hue.
  35667. */
  35668. set: function (value) {
  35669. this._globalDensity = value;
  35670. this._dirty = true;
  35671. },
  35672. enumerable: true,
  35673. configurable: true
  35674. });
  35675. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35676. /**
  35677. * Gets the global Saturation value.
  35678. * 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.
  35679. */
  35680. get: function () {
  35681. return this._globalSaturation;
  35682. },
  35683. /**
  35684. * Sets the global Saturation value.
  35685. * 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.
  35686. */
  35687. set: function (value) {
  35688. this._globalSaturation = value;
  35689. this._dirty = true;
  35690. },
  35691. enumerable: true,
  35692. configurable: true
  35693. });
  35694. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35695. /**
  35696. * Gets the highlights Hue value.
  35697. * 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).
  35698. */
  35699. get: function () {
  35700. return this._highlightsHue;
  35701. },
  35702. /**
  35703. * Sets the highlights Hue value.
  35704. * 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).
  35705. */
  35706. set: function (value) {
  35707. this._highlightsHue = value;
  35708. this._dirty = true;
  35709. },
  35710. enumerable: true,
  35711. configurable: true
  35712. });
  35713. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35714. /**
  35715. * Gets the highlights Density value.
  35716. * 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.
  35717. * Values less than zero provide a filter of opposite hue.
  35718. */
  35719. get: function () {
  35720. return this._highlightsDensity;
  35721. },
  35722. /**
  35723. * Sets the highlights Density value.
  35724. * 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.
  35725. * Values less than zero provide a filter of opposite hue.
  35726. */
  35727. set: function (value) {
  35728. this._highlightsDensity = value;
  35729. this._dirty = true;
  35730. },
  35731. enumerable: true,
  35732. configurable: true
  35733. });
  35734. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35735. /**
  35736. * Gets the highlights Saturation value.
  35737. * 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.
  35738. */
  35739. get: function () {
  35740. return this._highlightsSaturation;
  35741. },
  35742. /**
  35743. * Sets the highlights Saturation value.
  35744. * 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.
  35745. */
  35746. set: function (value) {
  35747. this._highlightsSaturation = value;
  35748. this._dirty = true;
  35749. },
  35750. enumerable: true,
  35751. configurable: true
  35752. });
  35753. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35754. /**
  35755. * Gets the highlights Exposure value.
  35756. * 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.
  35757. */
  35758. get: function () {
  35759. return this._highlightsExposure;
  35760. },
  35761. /**
  35762. * Sets the highlights Exposure value.
  35763. * 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.
  35764. */
  35765. set: function (value) {
  35766. this._highlightsExposure = value;
  35767. this._dirty = true;
  35768. },
  35769. enumerable: true,
  35770. configurable: true
  35771. });
  35772. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35773. /**
  35774. * Gets the midtones Hue value.
  35775. * 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).
  35776. */
  35777. get: function () {
  35778. return this._midtonesHue;
  35779. },
  35780. /**
  35781. * Sets the midtones Hue value.
  35782. * 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).
  35783. */
  35784. set: function (value) {
  35785. this._midtonesHue = value;
  35786. this._dirty = true;
  35787. },
  35788. enumerable: true,
  35789. configurable: true
  35790. });
  35791. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35792. /**
  35793. * Gets the midtones Density value.
  35794. * 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.
  35795. * Values less than zero provide a filter of opposite hue.
  35796. */
  35797. get: function () {
  35798. return this._midtonesDensity;
  35799. },
  35800. /**
  35801. * Sets the midtones Density value.
  35802. * 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.
  35803. * Values less than zero provide a filter of opposite hue.
  35804. */
  35805. set: function (value) {
  35806. this._midtonesDensity = value;
  35807. this._dirty = true;
  35808. },
  35809. enumerable: true,
  35810. configurable: true
  35811. });
  35812. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35813. /**
  35814. * Gets the midtones Saturation value.
  35815. * 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.
  35816. */
  35817. get: function () {
  35818. return this._midtonesSaturation;
  35819. },
  35820. /**
  35821. * Sets the midtones Saturation value.
  35822. * 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.
  35823. */
  35824. set: function (value) {
  35825. this._midtonesSaturation = value;
  35826. this._dirty = true;
  35827. },
  35828. enumerable: true,
  35829. configurable: true
  35830. });
  35831. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35832. /**
  35833. * Gets the midtones Exposure value.
  35834. * 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.
  35835. */
  35836. get: function () {
  35837. return this._midtonesExposure;
  35838. },
  35839. /**
  35840. * Sets the midtones Exposure value.
  35841. * 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.
  35842. */
  35843. set: function (value) {
  35844. this._midtonesExposure = value;
  35845. this._dirty = true;
  35846. },
  35847. enumerable: true,
  35848. configurable: true
  35849. });
  35850. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35851. /**
  35852. * Gets the shadows Hue value.
  35853. * 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).
  35854. */
  35855. get: function () {
  35856. return this._shadowsHue;
  35857. },
  35858. /**
  35859. * Sets the shadows Hue value.
  35860. * 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).
  35861. */
  35862. set: function (value) {
  35863. this._shadowsHue = value;
  35864. this._dirty = true;
  35865. },
  35866. enumerable: true,
  35867. configurable: true
  35868. });
  35869. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35870. /**
  35871. * Gets the shadows Density value.
  35872. * 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.
  35873. * Values less than zero provide a filter of opposite hue.
  35874. */
  35875. get: function () {
  35876. return this._shadowsDensity;
  35877. },
  35878. /**
  35879. * Sets the shadows Density value.
  35880. * 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.
  35881. * Values less than zero provide a filter of opposite hue.
  35882. */
  35883. set: function (value) {
  35884. this._shadowsDensity = value;
  35885. this._dirty = true;
  35886. },
  35887. enumerable: true,
  35888. configurable: true
  35889. });
  35890. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35891. /**
  35892. * Gets the shadows Saturation value.
  35893. * 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.
  35894. */
  35895. get: function () {
  35896. return this._shadowsSaturation;
  35897. },
  35898. /**
  35899. * Sets the shadows Saturation value.
  35900. * 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.
  35901. */
  35902. set: function (value) {
  35903. this._shadowsSaturation = value;
  35904. this._dirty = true;
  35905. },
  35906. enumerable: true,
  35907. configurable: true
  35908. });
  35909. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35910. /**
  35911. * Gets the shadows Exposure value.
  35912. * 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.
  35913. */
  35914. get: function () {
  35915. return this._shadowsExposure;
  35916. },
  35917. /**
  35918. * Sets the shadows Exposure value.
  35919. * 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.
  35920. */
  35921. set: function (value) {
  35922. this._shadowsExposure = value;
  35923. this._dirty = true;
  35924. },
  35925. enumerable: true,
  35926. configurable: true
  35927. });
  35928. ColorCurves.prototype.getClassName = function () {
  35929. return "ColorCurves";
  35930. };
  35931. /**
  35932. * Binds the color curves to the shader.
  35933. * @param colorCurves The color curve to bind
  35934. * @param effect The effect to bind to
  35935. */
  35936. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35937. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35938. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35939. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35940. if (colorCurves._dirty) {
  35941. colorCurves._dirty = false;
  35942. // Fill in global info.
  35943. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35944. // Compute highlights info.
  35945. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35946. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35947. // Compute midtones info.
  35948. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35949. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35950. // Compute shadows info.
  35951. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35952. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35953. // Compute deltas (neutral is midtones).
  35954. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35955. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35956. }
  35957. if (effect) {
  35958. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35959. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35960. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35961. }
  35962. };
  35963. /**
  35964. * Prepare the list of uniforms associated with the ColorCurves effects.
  35965. * @param uniformsList The list of uniforms used in the effect
  35966. */
  35967. ColorCurves.PrepareUniforms = function (uniformsList) {
  35968. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35969. };
  35970. /**
  35971. * Returns color grading data based on a hue, density, saturation and exposure value.
  35972. * @param filterHue The hue of the color filter.
  35973. * @param filterDensity The density of the color filter.
  35974. * @param saturation The saturation.
  35975. * @param exposure The exposure.
  35976. * @param result The result data container.
  35977. */
  35978. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35979. if (hue == null) {
  35980. return;
  35981. }
  35982. hue = ColorCurves.clamp(hue, 0, 360);
  35983. density = ColorCurves.clamp(density, -100, 100);
  35984. saturation = ColorCurves.clamp(saturation, -100, 100);
  35985. exposure = ColorCurves.clamp(exposure, -100, 100);
  35986. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35987. // so that the maximum filter density is only 50% control. This provides fine control
  35988. // for small values and reasonable range.
  35989. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35990. density *= 0.5;
  35991. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35992. if (density < 0) {
  35993. density *= -1;
  35994. hue = (hue + 180) % 360;
  35995. }
  35996. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35997. result.scaleToRef(2, result);
  35998. result.a = 1 + 0.01 * saturation;
  35999. };
  36000. /**
  36001. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  36002. * @param value The input slider value in range [-100,100].
  36003. * @returns Adjusted value.
  36004. */
  36005. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  36006. value /= 100;
  36007. var x = Math.abs(value);
  36008. x = Math.pow(x, 2);
  36009. if (value < 0) {
  36010. x *= -1;
  36011. }
  36012. x *= 100;
  36013. return x;
  36014. };
  36015. /**
  36016. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  36017. * @param hue The hue (H) input.
  36018. * @param saturation The saturation (S) input.
  36019. * @param brightness The brightness (B) input.
  36020. * @result An RGBA color represented as Vector4.
  36021. */
  36022. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  36023. var h = ColorCurves.clamp(hue, 0, 360);
  36024. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  36025. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  36026. if (s === 0) {
  36027. result.r = v;
  36028. result.g = v;
  36029. result.b = v;
  36030. }
  36031. else {
  36032. // sector 0 to 5
  36033. h /= 60;
  36034. var i = Math.floor(h);
  36035. // fractional part of h
  36036. var f = h - i;
  36037. var p = v * (1 - s);
  36038. var q = v * (1 - s * f);
  36039. var t = v * (1 - s * (1 - f));
  36040. switch (i) {
  36041. case 0:
  36042. result.r = v;
  36043. result.g = t;
  36044. result.b = p;
  36045. break;
  36046. case 1:
  36047. result.r = q;
  36048. result.g = v;
  36049. result.b = p;
  36050. break;
  36051. case 2:
  36052. result.r = p;
  36053. result.g = v;
  36054. result.b = t;
  36055. break;
  36056. case 3:
  36057. result.r = p;
  36058. result.g = q;
  36059. result.b = v;
  36060. break;
  36061. case 4:
  36062. result.r = t;
  36063. result.g = p;
  36064. result.b = v;
  36065. break;
  36066. default:// case 5:
  36067. result.r = v;
  36068. result.g = p;
  36069. result.b = q;
  36070. break;
  36071. }
  36072. }
  36073. result.a = 1;
  36074. };
  36075. /**
  36076. * Returns a value clamped between min and max
  36077. * @param value The value to clamp
  36078. * @param min The minimum of value
  36079. * @param max The maximum of value
  36080. * @returns The clamped value.
  36081. */
  36082. ColorCurves.clamp = function (value, min, max) {
  36083. return Math.min(Math.max(value, min), max);
  36084. };
  36085. /**
  36086. * Clones the current color curve instance.
  36087. * @return The cloned curves
  36088. */
  36089. ColorCurves.prototype.clone = function () {
  36090. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  36091. };
  36092. /**
  36093. * Serializes the current color curve instance to a json representation.
  36094. * @return a JSON representation
  36095. */
  36096. ColorCurves.prototype.serialize = function () {
  36097. return BABYLON.SerializationHelper.Serialize(this);
  36098. };
  36099. /**
  36100. * Parses the color curve from a json representation.
  36101. * @param source the JSON source to parse
  36102. * @return The parsed curves
  36103. */
  36104. ColorCurves.Parse = function (source) {
  36105. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  36106. };
  36107. __decorate([
  36108. BABYLON.serialize()
  36109. ], ColorCurves.prototype, "_globalHue", void 0);
  36110. __decorate([
  36111. BABYLON.serialize()
  36112. ], ColorCurves.prototype, "_globalDensity", void 0);
  36113. __decorate([
  36114. BABYLON.serialize()
  36115. ], ColorCurves.prototype, "_globalSaturation", void 0);
  36116. __decorate([
  36117. BABYLON.serialize()
  36118. ], ColorCurves.prototype, "_globalExposure", void 0);
  36119. __decorate([
  36120. BABYLON.serialize()
  36121. ], ColorCurves.prototype, "_highlightsHue", void 0);
  36122. __decorate([
  36123. BABYLON.serialize()
  36124. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  36125. __decorate([
  36126. BABYLON.serialize()
  36127. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  36128. __decorate([
  36129. BABYLON.serialize()
  36130. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  36131. __decorate([
  36132. BABYLON.serialize()
  36133. ], ColorCurves.prototype, "_midtonesHue", void 0);
  36134. __decorate([
  36135. BABYLON.serialize()
  36136. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  36137. __decorate([
  36138. BABYLON.serialize()
  36139. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  36140. __decorate([
  36141. BABYLON.serialize()
  36142. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  36143. return ColorCurves;
  36144. }());
  36145. BABYLON.ColorCurves = ColorCurves;
  36146. })(BABYLON || (BABYLON = {}));
  36147. //# sourceMappingURL=babylon.colorCurves.js.map
  36148. //# sourceMappingURL=babylon.behavior.js.map
  36149. var BABYLON;
  36150. (function (BABYLON) {
  36151. /**
  36152. * "Static Class" containing the most commonly used helper while dealing with material for
  36153. * rendering purpose.
  36154. *
  36155. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  36156. *
  36157. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  36158. */
  36159. var MaterialHelper = /** @class */ (function () {
  36160. function MaterialHelper() {
  36161. }
  36162. /**
  36163. * Bind the current view position to an effect.
  36164. * @param effect The effect to be bound
  36165. * @param scene The scene the eyes position is used from
  36166. */
  36167. MaterialHelper.BindEyePosition = function (effect, scene) {
  36168. if (scene._forcedViewPosition) {
  36169. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  36170. return;
  36171. }
  36172. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36173. };
  36174. /**
  36175. * Helps preparing the defines values about the UVs in used in the effect.
  36176. * UVs are shared as much as we can accross chanels in the shaders.
  36177. * @param texture The texture we are preparing the UVs for
  36178. * @param defines The defines to update
  36179. * @param key The chanel key "diffuse", "specular"... used in the shader
  36180. */
  36181. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  36182. defines._needUVs = true;
  36183. defines[key] = true;
  36184. if (texture.getTextureMatrix().isIdentity(true)) {
  36185. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  36186. if (texture.coordinatesIndex === 0) {
  36187. defines["MAINUV1"] = true;
  36188. }
  36189. else {
  36190. defines["MAINUV2"] = true;
  36191. }
  36192. }
  36193. else {
  36194. defines[key + "DIRECTUV"] = 0;
  36195. }
  36196. };
  36197. /**
  36198. * Binds a texture matrix value to its corrsponding uniform
  36199. * @param texture The texture to bind the matrix for
  36200. * @param uniformBuffer The uniform buffer receivin the data
  36201. * @param key The chanel key "diffuse", "specular"... used in the shader
  36202. */
  36203. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  36204. var matrix = texture.getTextureMatrix();
  36205. if (!matrix.isIdentity(true)) {
  36206. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  36207. }
  36208. };
  36209. /**
  36210. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  36211. * @param mesh defines the current mesh
  36212. * @param scene defines the current scene
  36213. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  36214. * @param pointsCloud defines if point cloud rendering has to be turned on
  36215. * @param fogEnabled defines if fog has to be turned on
  36216. * @param alphaTest defines if alpha testing has to be turned on
  36217. * @param defines defines the current list of defines
  36218. */
  36219. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  36220. if (defines._areMiscDirty) {
  36221. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  36222. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  36223. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  36224. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  36225. defines["ALPHATEST"] = alphaTest;
  36226. }
  36227. };
  36228. /**
  36229. * Helper used to prepare the list of defines associated with frame values for shader compilation
  36230. * @param scene defines the current scene
  36231. * @param engine defines the current engine
  36232. * @param defines specifies the list of active defines
  36233. * @param useInstances defines if instances have to be turned on
  36234. */
  36235. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  36236. var changed = false;
  36237. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  36238. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  36239. changed = true;
  36240. }
  36241. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  36242. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  36243. changed = true;
  36244. }
  36245. if (defines["INSTANCES"] !== useInstances) {
  36246. defines["INSTANCES"] = useInstances;
  36247. changed = true;
  36248. }
  36249. if (changed) {
  36250. defines.markAsUnprocessed();
  36251. }
  36252. };
  36253. /**
  36254. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  36255. * @param mesh The mesh containing the geometry data we will draw
  36256. * @param defines The defines to update
  36257. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  36258. * @param useBones Precise whether bones should be used or not (override mesh info)
  36259. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  36260. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  36261. * @returns false if defines are considered not dirty and have not been checked
  36262. */
  36263. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  36264. if (useMorphTargets === void 0) { useMorphTargets = false; }
  36265. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  36266. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  36267. return false;
  36268. }
  36269. defines._normals = defines._needNormals;
  36270. defines._uvs = defines._needUVs;
  36271. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  36272. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36273. defines["TANGENT"] = true;
  36274. }
  36275. if (defines._needUVs) {
  36276. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  36277. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  36278. }
  36279. else {
  36280. defines["UV1"] = false;
  36281. defines["UV2"] = false;
  36282. }
  36283. if (useVertexColor) {
  36284. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  36285. defines["VERTEXCOLOR"] = hasVertexColors;
  36286. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  36287. }
  36288. if (useBones) {
  36289. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36290. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  36291. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  36292. }
  36293. else {
  36294. defines["NUM_BONE_INFLUENCERS"] = 0;
  36295. defines["BonesPerMesh"] = 0;
  36296. }
  36297. }
  36298. if (useMorphTargets) {
  36299. var manager = mesh.morphTargetManager;
  36300. if (manager) {
  36301. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  36302. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  36303. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  36304. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  36305. }
  36306. else {
  36307. defines["MORPHTARGETS_TANGENT"] = false;
  36308. defines["MORPHTARGETS_NORMAL"] = false;
  36309. defines["MORPHTARGETS"] = false;
  36310. defines["NUM_MORPH_INFLUENCERS"] = 0;
  36311. }
  36312. }
  36313. return true;
  36314. };
  36315. /**
  36316. * Prepares the defines related to the light information passed in parameter
  36317. * @param scene The scene we are intending to draw
  36318. * @param mesh The mesh the effect is compiling for
  36319. * @param defines The defines to update
  36320. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  36321. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  36322. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  36323. * @returns true if normals will be required for the rest of the effect
  36324. */
  36325. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  36326. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36327. if (disableLighting === void 0) { disableLighting = false; }
  36328. if (!defines._areLightsDirty) {
  36329. return defines._needNormals;
  36330. }
  36331. var lightIndex = 0;
  36332. var needNormals = false;
  36333. var needRebuild = false;
  36334. var lightmapMode = false;
  36335. var shadowEnabled = false;
  36336. var specularEnabled = false;
  36337. if (scene.lightsEnabled && !disableLighting) {
  36338. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  36339. var light = _a[_i];
  36340. needNormals = true;
  36341. if (defines["LIGHT" + lightIndex] === undefined) {
  36342. needRebuild = true;
  36343. }
  36344. defines["LIGHT" + lightIndex] = true;
  36345. defines["SPOTLIGHT" + lightIndex] = false;
  36346. defines["HEMILIGHT" + lightIndex] = false;
  36347. defines["POINTLIGHT" + lightIndex] = false;
  36348. defines["DIRLIGHT" + lightIndex] = false;
  36349. var type;
  36350. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  36351. type = "SPOTLIGHT" + lightIndex;
  36352. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = light.projectedLightTexture ? true : false;
  36353. }
  36354. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  36355. type = "HEMILIGHT" + lightIndex;
  36356. }
  36357. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  36358. type = "POINTLIGHT" + lightIndex;
  36359. }
  36360. else {
  36361. type = "DIRLIGHT" + lightIndex;
  36362. }
  36363. defines[type] = true;
  36364. // Specular
  36365. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  36366. specularEnabled = true;
  36367. }
  36368. // Shadows
  36369. defines["SHADOW" + lightIndex] = false;
  36370. defines["SHADOWPCF" + lightIndex] = false;
  36371. defines["SHADOWESM" + lightIndex] = false;
  36372. defines["SHADOWCUBE" + lightIndex] = false;
  36373. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  36374. var shadowGenerator = light.getShadowGenerator();
  36375. if (shadowGenerator) {
  36376. shadowEnabled = true;
  36377. shadowGenerator.prepareDefines(defines, lightIndex);
  36378. }
  36379. }
  36380. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  36381. lightmapMode = true;
  36382. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  36383. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  36384. }
  36385. else {
  36386. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  36387. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  36388. }
  36389. lightIndex++;
  36390. if (lightIndex === maxSimultaneousLights)
  36391. break;
  36392. }
  36393. }
  36394. defines["SPECULARTERM"] = specularEnabled;
  36395. defines["SHADOWS"] = shadowEnabled;
  36396. // Resetting all other lights if any
  36397. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  36398. if (defines["LIGHT" + index] !== undefined) {
  36399. defines["LIGHT" + index] = false;
  36400. defines["HEMILIGHT" + lightIndex] = false;
  36401. defines["POINTLIGHT" + lightIndex] = false;
  36402. defines["DIRLIGHT" + lightIndex] = false;
  36403. defines["SPOTLIGHT" + lightIndex] = false;
  36404. defines["SHADOW" + lightIndex] = false;
  36405. }
  36406. }
  36407. var caps = scene.getEngine().getCaps();
  36408. if (defines["SHADOWFLOAT"] === undefined) {
  36409. needRebuild = true;
  36410. }
  36411. defines["SHADOWFLOAT"] = shadowEnabled &&
  36412. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  36413. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  36414. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  36415. if (needRebuild) {
  36416. defines.rebuild();
  36417. }
  36418. return needNormals;
  36419. };
  36420. /**
  36421. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  36422. * that won t be acctive due to defines being turned off.
  36423. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  36424. * @param samplersList The samplers list
  36425. * @param defines The defines helping in the list generation
  36426. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  36427. */
  36428. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  36429. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36430. var uniformsList;
  36431. var uniformBuffersList = null;
  36432. if (uniformsListOrOptions.uniformsNames) {
  36433. var options = uniformsListOrOptions;
  36434. uniformsList = options.uniformsNames;
  36435. uniformBuffersList = options.uniformBuffersNames;
  36436. samplersList = options.samplers;
  36437. defines = options.defines;
  36438. maxSimultaneousLights = options.maxSimultaneousLights;
  36439. }
  36440. else {
  36441. uniformsList = uniformsListOrOptions;
  36442. if (!samplersList) {
  36443. samplersList = [];
  36444. }
  36445. }
  36446. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36447. if (!defines["LIGHT" + lightIndex]) {
  36448. break;
  36449. }
  36450. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36451. if (uniformBuffersList) {
  36452. uniformBuffersList.push("Light" + lightIndex);
  36453. }
  36454. samplersList.push("shadowSampler" + lightIndex);
  36455. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  36456. samplersList.push("projectionLightSampler" + lightIndex);
  36457. uniformsList.push("textureProjectionMatrix" + lightIndex);
  36458. }
  36459. }
  36460. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36461. uniformsList.push("morphTargetInfluences");
  36462. }
  36463. };
  36464. /**
  36465. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  36466. * @param defines The defines to update while falling back
  36467. * @param fallbacks The authorized effect fallbacks
  36468. * @param maxSimultaneousLights The maximum number of lights allowed
  36469. * @param rank the current rank of the Effect
  36470. * @returns The newly affected rank
  36471. */
  36472. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36473. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36474. if (rank === void 0) { rank = 0; }
  36475. var lightFallbackRank = 0;
  36476. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36477. if (!defines["LIGHT" + lightIndex]) {
  36478. break;
  36479. }
  36480. if (lightIndex > 0) {
  36481. lightFallbackRank = rank + lightIndex;
  36482. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36483. }
  36484. if (!defines["SHADOWS"]) {
  36485. if (defines["SHADOW" + lightIndex]) {
  36486. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36487. }
  36488. if (defines["SHADOWPCF" + lightIndex]) {
  36489. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36490. }
  36491. if (defines["SHADOWESM" + lightIndex]) {
  36492. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36493. }
  36494. }
  36495. }
  36496. return lightFallbackRank++;
  36497. };
  36498. /**
  36499. * Prepares the list of attributes required for morph targets according to the effect defines.
  36500. * @param attribs The current list of supported attribs
  36501. * @param mesh The mesh to prepare the morph targets attributes for
  36502. * @param defines The current Defines of the effect
  36503. */
  36504. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36505. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36506. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36507. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36508. var manager = mesh.morphTargetManager;
  36509. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36510. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36511. for (var index = 0; index < influencers; index++) {
  36512. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36513. if (normal) {
  36514. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36515. }
  36516. if (tangent) {
  36517. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36518. }
  36519. if (attribs.length > maxAttributesCount) {
  36520. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36521. }
  36522. }
  36523. }
  36524. };
  36525. /**
  36526. * Prepares the list of attributes required for bones according to the effect defines.
  36527. * @param attribs The current list of supported attribs
  36528. * @param mesh The mesh to prepare the bones attributes for
  36529. * @param defines The current Defines of the effect
  36530. * @param fallbacks The current efffect fallback strategy
  36531. */
  36532. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36533. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36534. fallbacks.addCPUSkinningFallback(0, mesh);
  36535. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36536. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36537. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36538. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36539. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36540. }
  36541. }
  36542. };
  36543. /**
  36544. * Prepares the list of attributes required for instances according to the effect defines.
  36545. * @param attribs The current list of supported attribs
  36546. * @param defines The current Defines of the effect
  36547. */
  36548. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36549. if (defines["INSTANCES"]) {
  36550. attribs.push("world0");
  36551. attribs.push("world1");
  36552. attribs.push("world2");
  36553. attribs.push("world3");
  36554. }
  36555. };
  36556. /**
  36557. * Binds the light shadow information to the effect for the given mesh.
  36558. * @param light The light containing the generator
  36559. * @param scene The scene the lights belongs to
  36560. * @param mesh The mesh we are binding the information to render
  36561. * @param lightIndex The light index in the effect used to render the mesh
  36562. * @param effect The effect we are binding the data to
  36563. */
  36564. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36565. if (light.shadowEnabled && mesh.receiveShadows) {
  36566. var shadowGenerator = light.getShadowGenerator();
  36567. if (shadowGenerator) {
  36568. shadowGenerator.bindShadowLight(lightIndex, effect);
  36569. }
  36570. }
  36571. };
  36572. /**
  36573. * Binds the light information to the effect.
  36574. * @param light The light containing the generator
  36575. * @param effect The effect we are binding the data to
  36576. * @param lightIndex The light index in the effect used to render
  36577. */
  36578. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36579. light.transferToEffect(effect, lightIndex + "");
  36580. };
  36581. /**
  36582. * Binds the lights information from the scene to the effect for the given mesh.
  36583. * @param scene The scene the lights belongs to
  36584. * @param mesh The mesh we are binding the information to render
  36585. * @param effect The effect we are binding the data to
  36586. * @param defines The generated defines for the effect
  36587. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  36588. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  36589. */
  36590. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36591. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36592. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36593. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36594. for (var i = 0; i < len; i++) {
  36595. var light = mesh._lightSources[i];
  36596. var iAsString = i.toString();
  36597. var scaledIntensity = light.getScaledIntensity();
  36598. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36599. MaterialHelper.BindLightProperties(light, effect, i);
  36600. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36601. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36602. if (defines["SPECULARTERM"]) {
  36603. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36604. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36605. }
  36606. // Shadows
  36607. if (scene.shadowsEnabled) {
  36608. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36609. }
  36610. light._uniformBuffer.update();
  36611. }
  36612. };
  36613. /**
  36614. * Binds the fog information from the scene to the effect for the given mesh.
  36615. * @param scene The scene the lights belongs to
  36616. * @param mesh The mesh we are binding the information to render
  36617. * @param effect The effect we are binding the data to
  36618. */
  36619. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36620. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36621. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36622. effect.setColor3("vFogColor", scene.fogColor);
  36623. }
  36624. };
  36625. /**
  36626. * Binds the bones information from the mesh to the effect.
  36627. * @param mesh The mesh we are binding the information to render
  36628. * @param effect The effect we are binding the data to
  36629. */
  36630. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36631. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36632. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36633. if (matrices && effect) {
  36634. effect.setMatrices("mBones", matrices);
  36635. }
  36636. }
  36637. };
  36638. /**
  36639. * Binds the morph targets information from the mesh to the effect.
  36640. * @param abstractMesh The mesh we are binding the information to render
  36641. * @param effect The effect we are binding the data to
  36642. */
  36643. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36644. var manager = abstractMesh.morphTargetManager;
  36645. if (!abstractMesh || !manager) {
  36646. return;
  36647. }
  36648. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36649. };
  36650. /**
  36651. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  36652. * @param defines The generated defines used in the effect
  36653. * @param effect The effect we are binding the data to
  36654. * @param scene The scene we are willing to render with logarithmic scale for
  36655. */
  36656. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36657. if (defines["LOGARITHMICDEPTH"]) {
  36658. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36659. }
  36660. };
  36661. /**
  36662. * Binds the clip plane information from the scene to the effect.
  36663. * @param scene The scene the clip plane information are extracted from
  36664. * @param effect The effect we are binding the data to
  36665. */
  36666. MaterialHelper.BindClipPlane = function (effect, scene) {
  36667. if (scene.clipPlane) {
  36668. var clipPlane = scene.clipPlane;
  36669. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36670. }
  36671. };
  36672. return MaterialHelper;
  36673. }());
  36674. BABYLON.MaterialHelper = MaterialHelper;
  36675. })(BABYLON || (BABYLON = {}));
  36676. //# sourceMappingURL=babylon.materialHelper.js.map
  36677. var BABYLON;
  36678. (function (BABYLON) {
  36679. var PushMaterial = /** @class */ (function (_super) {
  36680. __extends(PushMaterial, _super);
  36681. function PushMaterial(name, scene) {
  36682. var _this = _super.call(this, name, scene) || this;
  36683. _this.storeEffectOnSubMeshes = true;
  36684. return _this;
  36685. }
  36686. PushMaterial.prototype.getEffect = function () {
  36687. return this._activeEffect;
  36688. };
  36689. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36690. if (!mesh) {
  36691. return false;
  36692. }
  36693. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36694. return true;
  36695. }
  36696. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36697. };
  36698. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36699. this._activeEffect.setMatrix("world", world);
  36700. };
  36701. PushMaterial.prototype.bind = function (world, mesh) {
  36702. if (!mesh) {
  36703. return;
  36704. }
  36705. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36706. };
  36707. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36708. if (effect === void 0) { effect = null; }
  36709. _super.prototype._afterBind.call(this, mesh);
  36710. this.getScene()._cachedEffect = effect;
  36711. };
  36712. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36713. if (visibility === void 0) { visibility = 1; }
  36714. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36715. };
  36716. return PushMaterial;
  36717. }(BABYLON.Material));
  36718. BABYLON.PushMaterial = PushMaterial;
  36719. })(BABYLON || (BABYLON = {}));
  36720. //# sourceMappingURL=babylon.pushMaterial.js.map
  36721. var BABYLON;
  36722. (function (BABYLON) {
  36723. var StandardMaterialDefines = /** @class */ (function (_super) {
  36724. __extends(StandardMaterialDefines, _super);
  36725. function StandardMaterialDefines() {
  36726. var _this = _super.call(this) || this;
  36727. _this.MAINUV1 = false;
  36728. _this.MAINUV2 = false;
  36729. _this.DIFFUSE = false;
  36730. _this.DIFFUSEDIRECTUV = 0;
  36731. _this.AMBIENT = false;
  36732. _this.AMBIENTDIRECTUV = 0;
  36733. _this.OPACITY = false;
  36734. _this.OPACITYDIRECTUV = 0;
  36735. _this.OPACITYRGB = false;
  36736. _this.REFLECTION = false;
  36737. _this.EMISSIVE = false;
  36738. _this.EMISSIVEDIRECTUV = 0;
  36739. _this.SPECULAR = false;
  36740. _this.SPECULARDIRECTUV = 0;
  36741. _this.BUMP = false;
  36742. _this.BUMPDIRECTUV = 0;
  36743. _this.PARALLAX = false;
  36744. _this.PARALLAXOCCLUSION = false;
  36745. _this.SPECULAROVERALPHA = false;
  36746. _this.CLIPPLANE = false;
  36747. _this.ALPHATEST = false;
  36748. _this.DEPTHPREPASS = false;
  36749. _this.ALPHAFROMDIFFUSE = false;
  36750. _this.POINTSIZE = false;
  36751. _this.FOG = false;
  36752. _this.SPECULARTERM = false;
  36753. _this.DIFFUSEFRESNEL = false;
  36754. _this.OPACITYFRESNEL = false;
  36755. _this.REFLECTIONFRESNEL = false;
  36756. _this.REFRACTIONFRESNEL = false;
  36757. _this.EMISSIVEFRESNEL = false;
  36758. _this.FRESNEL = false;
  36759. _this.NORMAL = false;
  36760. _this.UV1 = false;
  36761. _this.UV2 = false;
  36762. _this.VERTEXCOLOR = false;
  36763. _this.VERTEXALPHA = false;
  36764. _this.NUM_BONE_INFLUENCERS = 0;
  36765. _this.BonesPerMesh = 0;
  36766. _this.INSTANCES = false;
  36767. _this.GLOSSINESS = false;
  36768. _this.ROUGHNESS = false;
  36769. _this.EMISSIVEASILLUMINATION = false;
  36770. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36771. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36772. _this.LIGHTMAP = false;
  36773. _this.LIGHTMAPDIRECTUV = 0;
  36774. _this.USELIGHTMAPASSHADOWMAP = false;
  36775. _this.REFLECTIONMAP_3D = false;
  36776. _this.REFLECTIONMAP_SPHERICAL = false;
  36777. _this.REFLECTIONMAP_PLANAR = false;
  36778. _this.REFLECTIONMAP_CUBIC = false;
  36779. _this.REFLECTIONMAP_PROJECTION = false;
  36780. _this.REFLECTIONMAP_SKYBOX = false;
  36781. _this.REFLECTIONMAP_EXPLICIT = false;
  36782. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36783. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36784. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36785. _this.INVERTCUBICMAP = false;
  36786. _this.LOGARITHMICDEPTH = false;
  36787. _this.REFRACTION = false;
  36788. _this.REFRACTIONMAP_3D = false;
  36789. _this.REFLECTIONOVERALPHA = false;
  36790. _this.TWOSIDEDLIGHTING = false;
  36791. _this.SHADOWFLOAT = false;
  36792. _this.MORPHTARGETS = false;
  36793. _this.MORPHTARGETS_NORMAL = false;
  36794. _this.MORPHTARGETS_TANGENT = false;
  36795. _this.NUM_MORPH_INFLUENCERS = 0;
  36796. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36797. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36798. _this.IMAGEPROCESSING = false;
  36799. _this.VIGNETTE = false;
  36800. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36801. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36802. _this.TONEMAPPING = false;
  36803. _this.CONTRAST = false;
  36804. _this.COLORCURVES = false;
  36805. _this.COLORGRADING = false;
  36806. _this.COLORGRADING3D = false;
  36807. _this.SAMPLER3DGREENDEPTH = false;
  36808. _this.SAMPLER3DBGRMAP = false;
  36809. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36810. _this.EXPOSURE = false;
  36811. _this.rebuild();
  36812. return _this;
  36813. }
  36814. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36815. var modes = [
  36816. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36817. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36818. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36819. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36820. ];
  36821. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36822. var mode = modes_1[_i];
  36823. this[mode] = (mode === modeToEnable);
  36824. }
  36825. };
  36826. return StandardMaterialDefines;
  36827. }(BABYLON.MaterialDefines));
  36828. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36829. var StandardMaterial = /** @class */ (function (_super) {
  36830. __extends(StandardMaterial, _super);
  36831. function StandardMaterial(name, scene) {
  36832. var _this = _super.call(this, name, scene) || this;
  36833. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36834. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36835. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36836. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36837. _this.specularPower = 64;
  36838. _this._useAlphaFromDiffuseTexture = false;
  36839. _this._useEmissiveAsIllumination = false;
  36840. _this._linkEmissiveWithDiffuse = false;
  36841. _this._useSpecularOverAlpha = false;
  36842. _this._useReflectionOverAlpha = false;
  36843. _this._disableLighting = false;
  36844. _this._useParallax = false;
  36845. _this._useParallaxOcclusion = false;
  36846. _this.parallaxScaleBias = 0.05;
  36847. _this._roughness = 0;
  36848. _this.indexOfRefraction = 0.98;
  36849. _this.invertRefractionY = true;
  36850. _this._useLightmapAsShadowmap = false;
  36851. _this._useReflectionFresnelFromSpecular = false;
  36852. _this._useGlossinessFromSpecularMapAlpha = false;
  36853. _this._maxSimultaneousLights = 4;
  36854. /**
  36855. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36856. */
  36857. _this._invertNormalMapX = false;
  36858. /**
  36859. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36860. */
  36861. _this._invertNormalMapY = false;
  36862. /**
  36863. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36864. */
  36865. _this._twoSidedLighting = false;
  36866. _this._renderTargets = new BABYLON.SmartArray(16);
  36867. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36868. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36869. // Setup the default processing configuration to the scene.
  36870. _this._attachImageProcessingConfiguration(null);
  36871. _this.getRenderTargetTextures = function () {
  36872. _this._renderTargets.reset();
  36873. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36874. _this._renderTargets.push(_this._reflectionTexture);
  36875. }
  36876. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36877. _this._renderTargets.push(_this._refractionTexture);
  36878. }
  36879. return _this._renderTargets;
  36880. };
  36881. return _this;
  36882. }
  36883. ;
  36884. ;
  36885. ;
  36886. ;
  36887. ;
  36888. ;
  36889. ;
  36890. ;
  36891. ;
  36892. ;
  36893. ;
  36894. ;
  36895. ;
  36896. ;
  36897. ;
  36898. ;
  36899. ;
  36900. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36901. /**
  36902. * Gets the image processing configuration used either in this material.
  36903. */
  36904. get: function () {
  36905. return this._imageProcessingConfiguration;
  36906. },
  36907. /**
  36908. * Sets the Default image processing configuration used either in the this material.
  36909. *
  36910. * If sets to null, the scene one is in use.
  36911. */
  36912. set: function (value) {
  36913. this._attachImageProcessingConfiguration(value);
  36914. // Ensure the effect will be rebuilt.
  36915. this._markAllSubMeshesAsTexturesDirty();
  36916. },
  36917. enumerable: true,
  36918. configurable: true
  36919. });
  36920. /**
  36921. * Attaches a new image processing configuration to the Standard Material.
  36922. * @param configuration
  36923. */
  36924. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36925. var _this = this;
  36926. if (configuration === this._imageProcessingConfiguration) {
  36927. return;
  36928. }
  36929. // Detaches observer.
  36930. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36931. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36932. }
  36933. // Pick the scene configuration if needed.
  36934. if (!configuration) {
  36935. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36936. }
  36937. else {
  36938. this._imageProcessingConfiguration = configuration;
  36939. }
  36940. // Attaches observer.
  36941. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36942. _this._markAllSubMeshesAsImageProcessingDirty();
  36943. });
  36944. };
  36945. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36946. /**
  36947. * Gets wether the color curves effect is enabled.
  36948. */
  36949. get: function () {
  36950. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36951. },
  36952. /**
  36953. * Sets wether the color curves effect is enabled.
  36954. */
  36955. set: function (value) {
  36956. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36957. },
  36958. enumerable: true,
  36959. configurable: true
  36960. });
  36961. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36962. /**
  36963. * Gets wether the color grading effect is enabled.
  36964. */
  36965. get: function () {
  36966. return this.imageProcessingConfiguration.colorGradingEnabled;
  36967. },
  36968. /**
  36969. * Gets wether the color grading effect is enabled.
  36970. */
  36971. set: function (value) {
  36972. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36973. },
  36974. enumerable: true,
  36975. configurable: true
  36976. });
  36977. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36978. /**
  36979. * Gets wether tonemapping is enabled or not.
  36980. */
  36981. get: function () {
  36982. return this._imageProcessingConfiguration.toneMappingEnabled;
  36983. },
  36984. /**
  36985. * Sets wether tonemapping is enabled or not
  36986. */
  36987. set: function (value) {
  36988. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36989. },
  36990. enumerable: true,
  36991. configurable: true
  36992. });
  36993. ;
  36994. ;
  36995. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36996. /**
  36997. * The camera exposure used on this material.
  36998. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36999. * This corresponds to a photographic exposure.
  37000. */
  37001. get: function () {
  37002. return this._imageProcessingConfiguration.exposure;
  37003. },
  37004. /**
  37005. * The camera exposure used on this material.
  37006. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37007. * This corresponds to a photographic exposure.
  37008. */
  37009. set: function (value) {
  37010. this._imageProcessingConfiguration.exposure = value;
  37011. },
  37012. enumerable: true,
  37013. configurable: true
  37014. });
  37015. ;
  37016. ;
  37017. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  37018. /**
  37019. * Gets The camera contrast used on this material.
  37020. */
  37021. get: function () {
  37022. return this._imageProcessingConfiguration.contrast;
  37023. },
  37024. /**
  37025. * Sets The camera contrast used on this material.
  37026. */
  37027. set: function (value) {
  37028. this._imageProcessingConfiguration.contrast = value;
  37029. },
  37030. enumerable: true,
  37031. configurable: true
  37032. });
  37033. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  37034. /**
  37035. * Gets the Color Grading 2D Lookup Texture.
  37036. */
  37037. get: function () {
  37038. return this._imageProcessingConfiguration.colorGradingTexture;
  37039. },
  37040. /**
  37041. * Sets the Color Grading 2D Lookup Texture.
  37042. */
  37043. set: function (value) {
  37044. this._imageProcessingConfiguration.colorGradingTexture = value;
  37045. },
  37046. enumerable: true,
  37047. configurable: true
  37048. });
  37049. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  37050. /**
  37051. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37052. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37053. * 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;
  37054. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37055. */
  37056. get: function () {
  37057. return this._imageProcessingConfiguration.colorCurves;
  37058. },
  37059. /**
  37060. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37061. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37062. * 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;
  37063. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37064. */
  37065. set: function (value) {
  37066. this._imageProcessingConfiguration.colorCurves = value;
  37067. },
  37068. enumerable: true,
  37069. configurable: true
  37070. });
  37071. StandardMaterial.prototype.getClassName = function () {
  37072. return "StandardMaterial";
  37073. };
  37074. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  37075. get: function () {
  37076. return this._useLogarithmicDepth;
  37077. },
  37078. set: function (value) {
  37079. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37080. this._markAllSubMeshesAsMiscDirty();
  37081. },
  37082. enumerable: true,
  37083. configurable: true
  37084. });
  37085. StandardMaterial.prototype.needAlphaBlending = function () {
  37086. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  37087. };
  37088. StandardMaterial.prototype.needAlphaTesting = function () {
  37089. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  37090. };
  37091. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  37092. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  37093. };
  37094. StandardMaterial.prototype.getAlphaTestTexture = function () {
  37095. return this._diffuseTexture;
  37096. };
  37097. /**
  37098. * Child classes can use it to update shaders
  37099. */
  37100. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37101. if (useInstances === void 0) { useInstances = false; }
  37102. if (subMesh.effect && this.isFrozen) {
  37103. if (this._wasPreviouslyReady && subMesh.effect) {
  37104. return true;
  37105. }
  37106. }
  37107. if (!subMesh._materialDefines) {
  37108. subMesh._materialDefines = new StandardMaterialDefines();
  37109. }
  37110. var scene = this.getScene();
  37111. var defines = subMesh._materialDefines;
  37112. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37113. if (defines._renderId === scene.getRenderId()) {
  37114. return true;
  37115. }
  37116. }
  37117. var engine = scene.getEngine();
  37118. // Lights
  37119. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37120. // Textures
  37121. if (defines._areTexturesDirty) {
  37122. defines._needUVs = false;
  37123. defines.MAINUV1 = false;
  37124. defines.MAINUV2 = false;
  37125. if (scene.texturesEnabled) {
  37126. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37127. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  37128. return false;
  37129. }
  37130. else {
  37131. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  37132. }
  37133. }
  37134. else {
  37135. defines.DIFFUSE = false;
  37136. }
  37137. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37138. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37139. return false;
  37140. }
  37141. else {
  37142. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37143. }
  37144. }
  37145. else {
  37146. defines.AMBIENT = false;
  37147. }
  37148. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37149. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37150. return false;
  37151. }
  37152. else {
  37153. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37154. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37155. }
  37156. }
  37157. else {
  37158. defines.OPACITY = false;
  37159. }
  37160. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37161. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  37162. return false;
  37163. }
  37164. else {
  37165. defines._needNormals = true;
  37166. defines.REFLECTION = true;
  37167. defines.ROUGHNESS = (this._roughness > 0);
  37168. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  37169. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  37170. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  37171. switch (this._reflectionTexture.coordinatesMode) {
  37172. case BABYLON.Texture.CUBIC_MODE:
  37173. case BABYLON.Texture.INVCUBIC_MODE:
  37174. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  37175. break;
  37176. case BABYLON.Texture.EXPLICIT_MODE:
  37177. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  37178. break;
  37179. case BABYLON.Texture.PLANAR_MODE:
  37180. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  37181. break;
  37182. case BABYLON.Texture.PROJECTION_MODE:
  37183. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  37184. break;
  37185. case BABYLON.Texture.SKYBOX_MODE:
  37186. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  37187. break;
  37188. case BABYLON.Texture.SPHERICAL_MODE:
  37189. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  37190. break;
  37191. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37192. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  37193. break;
  37194. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37195. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  37196. break;
  37197. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37198. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  37199. break;
  37200. }
  37201. }
  37202. }
  37203. else {
  37204. defines.REFLECTION = false;
  37205. }
  37206. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37207. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37208. return false;
  37209. }
  37210. else {
  37211. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37212. }
  37213. }
  37214. else {
  37215. defines.EMISSIVE = false;
  37216. }
  37217. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37218. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37219. return false;
  37220. }
  37221. else {
  37222. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37223. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37224. }
  37225. }
  37226. else {
  37227. defines.LIGHTMAP = false;
  37228. }
  37229. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37230. if (!this._specularTexture.isReadyOrNotBlocking()) {
  37231. return false;
  37232. }
  37233. else {
  37234. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  37235. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  37236. }
  37237. }
  37238. else {
  37239. defines.SPECULAR = false;
  37240. }
  37241. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  37242. // Bump texure can not be not blocking.
  37243. if (!this._bumpTexture.isReady()) {
  37244. return false;
  37245. }
  37246. else {
  37247. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37248. defines.PARALLAX = this._useParallax;
  37249. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  37250. }
  37251. }
  37252. else {
  37253. defines.BUMP = false;
  37254. }
  37255. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37256. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  37257. return false;
  37258. }
  37259. else {
  37260. defines._needUVs = true;
  37261. defines.REFRACTION = true;
  37262. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  37263. }
  37264. }
  37265. else {
  37266. defines.REFRACTION = false;
  37267. }
  37268. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  37269. }
  37270. else {
  37271. defines.DIFFUSE = false;
  37272. defines.AMBIENT = false;
  37273. defines.OPACITY = false;
  37274. defines.REFLECTION = false;
  37275. defines.EMISSIVE = false;
  37276. defines.LIGHTMAP = false;
  37277. defines.BUMP = false;
  37278. defines.REFRACTION = false;
  37279. }
  37280. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  37281. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  37282. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  37283. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37284. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37285. }
  37286. if (defines._areImageProcessingDirty) {
  37287. if (!this._imageProcessingConfiguration.isReady()) {
  37288. return false;
  37289. }
  37290. this._imageProcessingConfiguration.prepareDefines(defines);
  37291. }
  37292. if (defines._areFresnelDirty) {
  37293. if (StandardMaterial.FresnelEnabled) {
  37294. // Fresnel
  37295. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  37296. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  37297. this._reflectionFresnelParameters) {
  37298. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  37299. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  37300. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  37301. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  37302. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  37303. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  37304. defines._needNormals = true;
  37305. defines.FRESNEL = true;
  37306. }
  37307. }
  37308. else {
  37309. defines.FRESNEL = false;
  37310. }
  37311. }
  37312. // Misc.
  37313. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  37314. // Attribs
  37315. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  37316. // Values that need to be evaluated on every frame
  37317. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  37318. // Get correct effect
  37319. if (defines.isDirty) {
  37320. defines.markAsProcessed();
  37321. scene.resetCachedMaterial();
  37322. // Fallbacks
  37323. var fallbacks = new BABYLON.EffectFallbacks();
  37324. if (defines.REFLECTION) {
  37325. fallbacks.addFallback(0, "REFLECTION");
  37326. }
  37327. if (defines.SPECULAR) {
  37328. fallbacks.addFallback(0, "SPECULAR");
  37329. }
  37330. if (defines.BUMP) {
  37331. fallbacks.addFallback(0, "BUMP");
  37332. }
  37333. if (defines.PARALLAX) {
  37334. fallbacks.addFallback(1, "PARALLAX");
  37335. }
  37336. if (defines.PARALLAXOCCLUSION) {
  37337. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37338. }
  37339. if (defines.SPECULAROVERALPHA) {
  37340. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37341. }
  37342. if (defines.FOG) {
  37343. fallbacks.addFallback(1, "FOG");
  37344. }
  37345. if (defines.POINTSIZE) {
  37346. fallbacks.addFallback(0, "POINTSIZE");
  37347. }
  37348. if (defines.LOGARITHMICDEPTH) {
  37349. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37350. }
  37351. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37352. if (defines.SPECULARTERM) {
  37353. fallbacks.addFallback(0, "SPECULARTERM");
  37354. }
  37355. if (defines.DIFFUSEFRESNEL) {
  37356. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  37357. }
  37358. if (defines.OPACITYFRESNEL) {
  37359. fallbacks.addFallback(2, "OPACITYFRESNEL");
  37360. }
  37361. if (defines.REFLECTIONFRESNEL) {
  37362. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  37363. }
  37364. if (defines.EMISSIVEFRESNEL) {
  37365. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  37366. }
  37367. if (defines.FRESNEL) {
  37368. fallbacks.addFallback(4, "FRESNEL");
  37369. }
  37370. //Attributes
  37371. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37372. if (defines.NORMAL) {
  37373. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37374. }
  37375. if (defines.UV1) {
  37376. attribs.push(BABYLON.VertexBuffer.UVKind);
  37377. }
  37378. if (defines.UV2) {
  37379. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37380. }
  37381. if (defines.VERTEXCOLOR) {
  37382. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37383. }
  37384. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37385. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37386. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37387. var shaderName = "default";
  37388. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  37389. "vFogInfos", "vFogColor", "pointSize",
  37390. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37391. "mBones",
  37392. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37393. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  37394. "logarithmicDepthConstant", "vTangentSpaceParams"
  37395. ];
  37396. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  37397. var uniformBuffers = ["Material", "Scene"];
  37398. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37399. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37400. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37401. uniformsNames: uniforms,
  37402. uniformBuffersNames: uniformBuffers,
  37403. samplers: samplers,
  37404. defines: defines,
  37405. maxSimultaneousLights: this._maxSimultaneousLights
  37406. });
  37407. if (this.customShaderNameResolve) {
  37408. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  37409. }
  37410. var join = defines.toString();
  37411. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  37412. attributes: attribs,
  37413. uniformsNames: uniforms,
  37414. uniformBuffersNames: uniformBuffers,
  37415. samplers: samplers,
  37416. defines: join,
  37417. fallbacks: fallbacks,
  37418. onCompiled: this.onCompiled,
  37419. onError: this.onError,
  37420. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37421. }, engine), defines);
  37422. this.buildUniformLayout();
  37423. }
  37424. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37425. return false;
  37426. }
  37427. defines._renderId = scene.getRenderId();
  37428. this._wasPreviouslyReady = true;
  37429. return true;
  37430. };
  37431. StandardMaterial.prototype.buildUniformLayout = function () {
  37432. // Order is important !
  37433. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  37434. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  37435. this._uniformBuffer.addUniform("opacityParts", 4);
  37436. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  37437. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  37438. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  37439. this._uniformBuffer.addUniform("refractionRightColor", 4);
  37440. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  37441. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  37442. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  37443. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  37444. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37445. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37446. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37447. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37448. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  37449. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37450. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  37451. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37452. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37453. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37454. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37455. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37456. this._uniformBuffer.addUniform("specularMatrix", 16);
  37457. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37458. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37459. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37460. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37461. this._uniformBuffer.addUniform("vSpecularColor", 4);
  37462. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37463. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  37464. this._uniformBuffer.addUniform("pointSize", 1);
  37465. this._uniformBuffer.create();
  37466. };
  37467. StandardMaterial.prototype.unbind = function () {
  37468. if (this._activeEffect) {
  37469. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37470. this._activeEffect.setTexture("reflection2DSampler", null);
  37471. }
  37472. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37473. this._activeEffect.setTexture("refraction2DSampler", null);
  37474. }
  37475. }
  37476. _super.prototype.unbind.call(this);
  37477. };
  37478. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37479. var scene = this.getScene();
  37480. var defines = subMesh._materialDefines;
  37481. if (!defines) {
  37482. return;
  37483. }
  37484. var effect = subMesh.effect;
  37485. if (!effect) {
  37486. return;
  37487. }
  37488. this._activeEffect = effect;
  37489. // Matrices
  37490. this.bindOnlyWorldMatrix(world);
  37491. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37492. // Bones
  37493. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  37494. if (mustRebind) {
  37495. this._uniformBuffer.bindToEffect(effect, "Material");
  37496. this.bindViewProjection(effect);
  37497. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37498. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  37499. // Fresnel
  37500. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  37501. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  37502. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  37503. }
  37504. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  37505. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  37506. }
  37507. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  37508. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  37509. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  37510. }
  37511. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  37512. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  37513. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  37514. }
  37515. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  37516. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  37517. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  37518. }
  37519. }
  37520. // Textures
  37521. if (scene.texturesEnabled) {
  37522. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37523. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37524. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37525. }
  37526. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37527. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37528. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37529. }
  37530. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37531. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37532. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37533. }
  37534. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37535. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37536. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37537. }
  37538. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37539. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37540. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37541. }
  37542. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37543. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37544. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37545. }
  37546. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37547. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37548. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37549. }
  37550. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37551. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37552. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37553. if (scene._mirroredCameraPosition) {
  37554. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37555. }
  37556. else {
  37557. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37558. }
  37559. }
  37560. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37561. var depth = 1.0;
  37562. if (!this._refractionTexture.isCube) {
  37563. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37564. if (this._refractionTexture.depth) {
  37565. depth = this._refractionTexture.depth;
  37566. }
  37567. }
  37568. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37569. }
  37570. }
  37571. // Point size
  37572. if (this.pointsCloud) {
  37573. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37574. }
  37575. if (defines.SPECULARTERM) {
  37576. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37577. }
  37578. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37579. // Diffuse
  37580. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37581. }
  37582. // Textures
  37583. if (scene.texturesEnabled) {
  37584. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37585. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37586. }
  37587. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37588. effect.setTexture("ambientSampler", this._ambientTexture);
  37589. }
  37590. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37591. effect.setTexture("opacitySampler", this._opacityTexture);
  37592. }
  37593. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37594. if (this._reflectionTexture.isCube) {
  37595. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37596. }
  37597. else {
  37598. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37599. }
  37600. }
  37601. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37602. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37603. }
  37604. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37605. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37606. }
  37607. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37608. effect.setTexture("specularSampler", this._specularTexture);
  37609. }
  37610. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37611. effect.setTexture("bumpSampler", this._bumpTexture);
  37612. }
  37613. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37614. var depth = 1.0;
  37615. if (this._refractionTexture.isCube) {
  37616. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37617. }
  37618. else {
  37619. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37620. }
  37621. }
  37622. }
  37623. // Clip plane
  37624. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37625. // Colors
  37626. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37627. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37628. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37629. }
  37630. if (mustRebind || !this.isFrozen) {
  37631. // Lights
  37632. if (scene.lightsEnabled && !this._disableLighting) {
  37633. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37634. }
  37635. // View
  37636. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37637. this.bindView(effect);
  37638. }
  37639. // Fog
  37640. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37641. // Morph targets
  37642. if (defines.NUM_MORPH_INFLUENCERS) {
  37643. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37644. }
  37645. // Log. depth
  37646. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37647. // image processing
  37648. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37649. this._imageProcessingConfiguration.bind(this._activeEffect);
  37650. }
  37651. }
  37652. this._uniformBuffer.update();
  37653. this._afterBind(mesh, this._activeEffect);
  37654. };
  37655. StandardMaterial.prototype.getAnimatables = function () {
  37656. var results = [];
  37657. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37658. results.push(this._diffuseTexture);
  37659. }
  37660. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37661. results.push(this._ambientTexture);
  37662. }
  37663. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37664. results.push(this._opacityTexture);
  37665. }
  37666. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37667. results.push(this._reflectionTexture);
  37668. }
  37669. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37670. results.push(this._emissiveTexture);
  37671. }
  37672. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37673. results.push(this._specularTexture);
  37674. }
  37675. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37676. results.push(this._bumpTexture);
  37677. }
  37678. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37679. results.push(this._lightmapTexture);
  37680. }
  37681. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37682. results.push(this._refractionTexture);
  37683. }
  37684. return results;
  37685. };
  37686. StandardMaterial.prototype.getActiveTextures = function () {
  37687. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37688. if (this._diffuseTexture) {
  37689. activeTextures.push(this._diffuseTexture);
  37690. }
  37691. if (this._ambientTexture) {
  37692. activeTextures.push(this._ambientTexture);
  37693. }
  37694. if (this._opacityTexture) {
  37695. activeTextures.push(this._opacityTexture);
  37696. }
  37697. if (this._reflectionTexture) {
  37698. activeTextures.push(this._reflectionTexture);
  37699. }
  37700. if (this._emissiveTexture) {
  37701. activeTextures.push(this._emissiveTexture);
  37702. }
  37703. if (this._specularTexture) {
  37704. activeTextures.push(this._specularTexture);
  37705. }
  37706. if (this._bumpTexture) {
  37707. activeTextures.push(this._bumpTexture);
  37708. }
  37709. if (this._lightmapTexture) {
  37710. activeTextures.push(this._lightmapTexture);
  37711. }
  37712. if (this._refractionTexture) {
  37713. activeTextures.push(this._refractionTexture);
  37714. }
  37715. return activeTextures;
  37716. };
  37717. StandardMaterial.prototype.hasTexture = function (texture) {
  37718. if (_super.prototype.hasTexture.call(this, texture)) {
  37719. return true;
  37720. }
  37721. if (this._diffuseTexture === texture) {
  37722. return true;
  37723. }
  37724. if (this._ambientTexture === texture) {
  37725. return true;
  37726. }
  37727. if (this._opacityTexture === texture) {
  37728. return true;
  37729. }
  37730. if (this._reflectionTexture === texture) {
  37731. return true;
  37732. }
  37733. if (this._emissiveTexture === texture) {
  37734. return true;
  37735. }
  37736. if (this._specularTexture === texture) {
  37737. return true;
  37738. }
  37739. if (this._bumpTexture === texture) {
  37740. return true;
  37741. }
  37742. if (this._lightmapTexture === texture) {
  37743. return true;
  37744. }
  37745. if (this._refractionTexture === texture) {
  37746. return true;
  37747. }
  37748. return false;
  37749. };
  37750. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37751. if (forceDisposeTextures) {
  37752. if (this._diffuseTexture) {
  37753. this._diffuseTexture.dispose();
  37754. }
  37755. if (this._ambientTexture) {
  37756. this._ambientTexture.dispose();
  37757. }
  37758. if (this._opacityTexture) {
  37759. this._opacityTexture.dispose();
  37760. }
  37761. if (this._reflectionTexture) {
  37762. this._reflectionTexture.dispose();
  37763. }
  37764. if (this._emissiveTexture) {
  37765. this._emissiveTexture.dispose();
  37766. }
  37767. if (this._specularTexture) {
  37768. this._specularTexture.dispose();
  37769. }
  37770. if (this._bumpTexture) {
  37771. this._bumpTexture.dispose();
  37772. }
  37773. if (this._lightmapTexture) {
  37774. this._lightmapTexture.dispose();
  37775. }
  37776. if (this._refractionTexture) {
  37777. this._refractionTexture.dispose();
  37778. }
  37779. }
  37780. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37781. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37782. }
  37783. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37784. };
  37785. StandardMaterial.prototype.clone = function (name) {
  37786. var _this = this;
  37787. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37788. result.name = name;
  37789. result.id = name;
  37790. return result;
  37791. };
  37792. StandardMaterial.prototype.serialize = function () {
  37793. return BABYLON.SerializationHelper.Serialize(this);
  37794. };
  37795. // Statics
  37796. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37797. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37798. };
  37799. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37800. get: function () {
  37801. return StandardMaterial._DiffuseTextureEnabled;
  37802. },
  37803. set: function (value) {
  37804. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37805. return;
  37806. }
  37807. StandardMaterial._DiffuseTextureEnabled = value;
  37808. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37809. },
  37810. enumerable: true,
  37811. configurable: true
  37812. });
  37813. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37814. get: function () {
  37815. return StandardMaterial._AmbientTextureEnabled;
  37816. },
  37817. set: function (value) {
  37818. if (StandardMaterial._AmbientTextureEnabled === value) {
  37819. return;
  37820. }
  37821. StandardMaterial._AmbientTextureEnabled = value;
  37822. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37823. },
  37824. enumerable: true,
  37825. configurable: true
  37826. });
  37827. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37828. get: function () {
  37829. return StandardMaterial._OpacityTextureEnabled;
  37830. },
  37831. set: function (value) {
  37832. if (StandardMaterial._OpacityTextureEnabled === value) {
  37833. return;
  37834. }
  37835. StandardMaterial._OpacityTextureEnabled = value;
  37836. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37837. },
  37838. enumerable: true,
  37839. configurable: true
  37840. });
  37841. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37842. get: function () {
  37843. return StandardMaterial._ReflectionTextureEnabled;
  37844. },
  37845. set: function (value) {
  37846. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37847. return;
  37848. }
  37849. StandardMaterial._ReflectionTextureEnabled = value;
  37850. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37851. },
  37852. enumerable: true,
  37853. configurable: true
  37854. });
  37855. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37856. get: function () {
  37857. return StandardMaterial._EmissiveTextureEnabled;
  37858. },
  37859. set: function (value) {
  37860. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37861. return;
  37862. }
  37863. StandardMaterial._EmissiveTextureEnabled = value;
  37864. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37865. },
  37866. enumerable: true,
  37867. configurable: true
  37868. });
  37869. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37870. get: function () {
  37871. return StandardMaterial._SpecularTextureEnabled;
  37872. },
  37873. set: function (value) {
  37874. if (StandardMaterial._SpecularTextureEnabled === value) {
  37875. return;
  37876. }
  37877. StandardMaterial._SpecularTextureEnabled = value;
  37878. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37879. },
  37880. enumerable: true,
  37881. configurable: true
  37882. });
  37883. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37884. get: function () {
  37885. return StandardMaterial._BumpTextureEnabled;
  37886. },
  37887. set: function (value) {
  37888. if (StandardMaterial._BumpTextureEnabled === value) {
  37889. return;
  37890. }
  37891. StandardMaterial._BumpTextureEnabled = value;
  37892. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37893. },
  37894. enumerable: true,
  37895. configurable: true
  37896. });
  37897. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37898. get: function () {
  37899. return StandardMaterial._LightmapTextureEnabled;
  37900. },
  37901. set: function (value) {
  37902. if (StandardMaterial._LightmapTextureEnabled === value) {
  37903. return;
  37904. }
  37905. StandardMaterial._LightmapTextureEnabled = value;
  37906. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37907. },
  37908. enumerable: true,
  37909. configurable: true
  37910. });
  37911. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37912. get: function () {
  37913. return StandardMaterial._RefractionTextureEnabled;
  37914. },
  37915. set: function (value) {
  37916. if (StandardMaterial._RefractionTextureEnabled === value) {
  37917. return;
  37918. }
  37919. StandardMaterial._RefractionTextureEnabled = value;
  37920. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37921. },
  37922. enumerable: true,
  37923. configurable: true
  37924. });
  37925. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37926. get: function () {
  37927. return StandardMaterial._ColorGradingTextureEnabled;
  37928. },
  37929. set: function (value) {
  37930. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37931. return;
  37932. }
  37933. StandardMaterial._ColorGradingTextureEnabled = value;
  37934. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37935. },
  37936. enumerable: true,
  37937. configurable: true
  37938. });
  37939. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37940. get: function () {
  37941. return StandardMaterial._FresnelEnabled;
  37942. },
  37943. set: function (value) {
  37944. if (StandardMaterial._FresnelEnabled === value) {
  37945. return;
  37946. }
  37947. StandardMaterial._FresnelEnabled = value;
  37948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37949. },
  37950. enumerable: true,
  37951. configurable: true
  37952. });
  37953. // Flags used to enable or disable a type of texture for all Standard Materials
  37954. StandardMaterial._DiffuseTextureEnabled = true;
  37955. StandardMaterial._AmbientTextureEnabled = true;
  37956. StandardMaterial._OpacityTextureEnabled = true;
  37957. StandardMaterial._ReflectionTextureEnabled = true;
  37958. StandardMaterial._EmissiveTextureEnabled = true;
  37959. StandardMaterial._SpecularTextureEnabled = true;
  37960. StandardMaterial._BumpTextureEnabled = true;
  37961. StandardMaterial._LightmapTextureEnabled = true;
  37962. StandardMaterial._RefractionTextureEnabled = true;
  37963. StandardMaterial._ColorGradingTextureEnabled = true;
  37964. StandardMaterial._FresnelEnabled = true;
  37965. __decorate([
  37966. BABYLON.serializeAsTexture("diffuseTexture")
  37967. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37968. __decorate([
  37969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37970. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37971. __decorate([
  37972. BABYLON.serializeAsTexture("ambientTexture")
  37973. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37974. __decorate([
  37975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37976. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37977. __decorate([
  37978. BABYLON.serializeAsTexture("opacityTexture")
  37979. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37980. __decorate([
  37981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37982. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37983. __decorate([
  37984. BABYLON.serializeAsTexture("reflectionTexture")
  37985. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37986. __decorate([
  37987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37988. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37989. __decorate([
  37990. BABYLON.serializeAsTexture("emissiveTexture")
  37991. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37992. __decorate([
  37993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37994. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37995. __decorate([
  37996. BABYLON.serializeAsTexture("specularTexture")
  37997. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37998. __decorate([
  37999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38000. ], StandardMaterial.prototype, "specularTexture", void 0);
  38001. __decorate([
  38002. BABYLON.serializeAsTexture("bumpTexture")
  38003. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  38004. __decorate([
  38005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38006. ], StandardMaterial.prototype, "bumpTexture", void 0);
  38007. __decorate([
  38008. BABYLON.serializeAsTexture("lightmapTexture")
  38009. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  38010. __decorate([
  38011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38012. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  38013. __decorate([
  38014. BABYLON.serializeAsTexture("refractionTexture")
  38015. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  38016. __decorate([
  38017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38018. ], StandardMaterial.prototype, "refractionTexture", void 0);
  38019. __decorate([
  38020. BABYLON.serializeAsColor3("ambient")
  38021. ], StandardMaterial.prototype, "ambientColor", void 0);
  38022. __decorate([
  38023. BABYLON.serializeAsColor3("diffuse")
  38024. ], StandardMaterial.prototype, "diffuseColor", void 0);
  38025. __decorate([
  38026. BABYLON.serializeAsColor3("specular")
  38027. ], StandardMaterial.prototype, "specularColor", void 0);
  38028. __decorate([
  38029. BABYLON.serializeAsColor3("emissive")
  38030. ], StandardMaterial.prototype, "emissiveColor", void 0);
  38031. __decorate([
  38032. BABYLON.serialize()
  38033. ], StandardMaterial.prototype, "specularPower", void 0);
  38034. __decorate([
  38035. BABYLON.serialize("useAlphaFromDiffuseTexture")
  38036. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  38037. __decorate([
  38038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38039. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  38040. __decorate([
  38041. BABYLON.serialize("useEmissiveAsIllumination")
  38042. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  38043. __decorate([
  38044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38045. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  38046. __decorate([
  38047. BABYLON.serialize("linkEmissiveWithDiffuse")
  38048. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  38049. __decorate([
  38050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38051. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  38052. __decorate([
  38053. BABYLON.serialize("useSpecularOverAlpha")
  38054. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  38055. __decorate([
  38056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38057. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  38058. __decorate([
  38059. BABYLON.serialize("useReflectionOverAlpha")
  38060. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  38061. __decorate([
  38062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38063. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  38064. __decorate([
  38065. BABYLON.serialize("disableLighting")
  38066. ], StandardMaterial.prototype, "_disableLighting", void 0);
  38067. __decorate([
  38068. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38069. ], StandardMaterial.prototype, "disableLighting", void 0);
  38070. __decorate([
  38071. BABYLON.serialize("useParallax")
  38072. ], StandardMaterial.prototype, "_useParallax", void 0);
  38073. __decorate([
  38074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38075. ], StandardMaterial.prototype, "useParallax", void 0);
  38076. __decorate([
  38077. BABYLON.serialize("useParallaxOcclusion")
  38078. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  38079. __decorate([
  38080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38081. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  38082. __decorate([
  38083. BABYLON.serialize()
  38084. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  38085. __decorate([
  38086. BABYLON.serialize("roughness")
  38087. ], StandardMaterial.prototype, "_roughness", void 0);
  38088. __decorate([
  38089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38090. ], StandardMaterial.prototype, "roughness", void 0);
  38091. __decorate([
  38092. BABYLON.serialize()
  38093. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  38094. __decorate([
  38095. BABYLON.serialize()
  38096. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  38097. __decorate([
  38098. BABYLON.serialize("useLightmapAsShadowmap")
  38099. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  38100. __decorate([
  38101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38102. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38103. __decorate([
  38104. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  38105. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  38106. __decorate([
  38107. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38108. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  38109. __decorate([
  38110. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  38111. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  38112. __decorate([
  38113. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  38114. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  38115. __decorate([
  38116. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  38117. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  38118. __decorate([
  38119. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38120. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  38121. __decorate([
  38122. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  38123. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  38124. __decorate([
  38125. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38126. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  38127. __decorate([
  38128. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  38129. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  38130. __decorate([
  38131. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38132. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  38133. __decorate([
  38134. BABYLON.serialize("useReflectionFresnelFromSpecular")
  38135. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  38136. __decorate([
  38137. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  38138. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  38139. __decorate([
  38140. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  38141. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  38142. __decorate([
  38143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38144. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  38145. __decorate([
  38146. BABYLON.serialize("maxSimultaneousLights")
  38147. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  38148. __decorate([
  38149. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38150. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  38151. __decorate([
  38152. BABYLON.serialize("invertNormalMapX")
  38153. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  38154. __decorate([
  38155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38156. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  38157. __decorate([
  38158. BABYLON.serialize("invertNormalMapY")
  38159. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  38160. __decorate([
  38161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38162. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  38163. __decorate([
  38164. BABYLON.serialize("twoSidedLighting")
  38165. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  38166. __decorate([
  38167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38168. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  38169. __decorate([
  38170. BABYLON.serialize()
  38171. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  38172. return StandardMaterial;
  38173. }(BABYLON.PushMaterial));
  38174. BABYLON.StandardMaterial = StandardMaterial;
  38175. })(BABYLON || (BABYLON = {}));
  38176. //# sourceMappingURL=babylon.standardMaterial.js.map
  38177. var BABYLON;
  38178. (function (BABYLON) {
  38179. var PBRMaterialDefines = /** @class */ (function (_super) {
  38180. __extends(PBRMaterialDefines, _super);
  38181. function PBRMaterialDefines() {
  38182. var _this = _super.call(this) || this;
  38183. _this.PBR = true;
  38184. _this.MAINUV1 = false;
  38185. _this.MAINUV2 = false;
  38186. _this.UV1 = false;
  38187. _this.UV2 = false;
  38188. _this.ALBEDO = false;
  38189. _this.ALBEDODIRECTUV = 0;
  38190. _this.VERTEXCOLOR = false;
  38191. _this.AMBIENT = false;
  38192. _this.AMBIENTDIRECTUV = 0;
  38193. _this.AMBIENTINGRAYSCALE = false;
  38194. _this.OPACITY = false;
  38195. _this.VERTEXALPHA = false;
  38196. _this.OPACITYDIRECTUV = 0;
  38197. _this.OPACITYRGB = false;
  38198. _this.ALPHATEST = false;
  38199. _this.DEPTHPREPASS = false;
  38200. _this.ALPHABLEND = false;
  38201. _this.ALPHAFROMALBEDO = false;
  38202. _this.ALPHATESTVALUE = 0.5;
  38203. _this.SPECULAROVERALPHA = false;
  38204. _this.RADIANCEOVERALPHA = false;
  38205. _this.ALPHAFRESNEL = false;
  38206. _this.LINEARALPHAFRESNEL = false;
  38207. _this.PREMULTIPLYALPHA = false;
  38208. _this.EMISSIVE = false;
  38209. _this.EMISSIVEDIRECTUV = 0;
  38210. _this.REFLECTIVITY = false;
  38211. _this.REFLECTIVITYDIRECTUV = 0;
  38212. _this.SPECULARTERM = false;
  38213. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38214. _this.MICROSURFACEAUTOMATIC = false;
  38215. _this.LODBASEDMICROSFURACE = false;
  38216. _this.MICROSURFACEMAP = false;
  38217. _this.MICROSURFACEMAPDIRECTUV = 0;
  38218. _this.METALLICWORKFLOW = false;
  38219. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38220. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38221. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38222. _this.AOSTOREINMETALMAPRED = false;
  38223. _this.ENVIRONMENTBRDF = false;
  38224. _this.NORMAL = false;
  38225. _this.TANGENT = false;
  38226. _this.BUMP = false;
  38227. _this.BUMPDIRECTUV = 0;
  38228. _this.PARALLAX = false;
  38229. _this.PARALLAXOCCLUSION = false;
  38230. _this.NORMALXYSCALE = true;
  38231. _this.LIGHTMAP = false;
  38232. _this.LIGHTMAPDIRECTUV = 0;
  38233. _this.USELIGHTMAPASSHADOWMAP = false;
  38234. _this.REFLECTION = false;
  38235. _this.REFLECTIONMAP_3D = false;
  38236. _this.REFLECTIONMAP_SPHERICAL = false;
  38237. _this.REFLECTIONMAP_PLANAR = false;
  38238. _this.REFLECTIONMAP_CUBIC = false;
  38239. _this.REFLECTIONMAP_PROJECTION = false;
  38240. _this.REFLECTIONMAP_SKYBOX = false;
  38241. _this.REFLECTIONMAP_EXPLICIT = false;
  38242. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38243. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38244. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38245. _this.INVERTCUBICMAP = false;
  38246. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38247. _this.USESPHERICALINVERTEX = false;
  38248. _this.REFLECTIONMAP_OPPOSITEZ = false;
  38249. _this.LODINREFLECTIONALPHA = false;
  38250. _this.GAMMAREFLECTION = false;
  38251. _this.RADIANCEOCCLUSION = false;
  38252. _this.HORIZONOCCLUSION = false;
  38253. _this.REFRACTION = false;
  38254. _this.REFRACTIONMAP_3D = false;
  38255. _this.REFRACTIONMAP_OPPOSITEZ = false;
  38256. _this.LODINREFRACTIONALPHA = false;
  38257. _this.GAMMAREFRACTION = false;
  38258. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38259. _this.INSTANCES = false;
  38260. _this.NUM_BONE_INFLUENCERS = 0;
  38261. _this.BonesPerMesh = 0;
  38262. _this.NONUNIFORMSCALING = false;
  38263. _this.MORPHTARGETS = false;
  38264. _this.MORPHTARGETS_NORMAL = false;
  38265. _this.MORPHTARGETS_TANGENT = false;
  38266. _this.NUM_MORPH_INFLUENCERS = 0;
  38267. _this.IMAGEPROCESSING = false;
  38268. _this.VIGNETTE = false;
  38269. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38270. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38271. _this.TONEMAPPING = false;
  38272. _this.CONTRAST = false;
  38273. _this.COLORCURVES = false;
  38274. _this.COLORGRADING = false;
  38275. _this.COLORGRADING3D = false;
  38276. _this.SAMPLER3DGREENDEPTH = false;
  38277. _this.SAMPLER3DBGRMAP = false;
  38278. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38279. _this.EXPOSURE = false;
  38280. _this.USEPHYSICALLIGHTFALLOFF = false;
  38281. _this.TWOSIDEDLIGHTING = false;
  38282. _this.SHADOWFLOAT = false;
  38283. _this.CLIPPLANE = false;
  38284. _this.POINTSIZE = false;
  38285. _this.FOG = false;
  38286. _this.LOGARITHMICDEPTH = false;
  38287. _this.FORCENORMALFORWARD = false;
  38288. _this.rebuild();
  38289. return _this;
  38290. }
  38291. PBRMaterialDefines.prototype.reset = function () {
  38292. _super.prototype.reset.call(this);
  38293. this.ALPHATESTVALUE = 0.5;
  38294. this.PBR = true;
  38295. };
  38296. return PBRMaterialDefines;
  38297. }(BABYLON.MaterialDefines));
  38298. /**
  38299. * The Physically based material base class of BJS.
  38300. *
  38301. * This offers the main features of a standard PBR material.
  38302. * For more information, please refer to the documentation :
  38303. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38304. */
  38305. var PBRBaseMaterial = /** @class */ (function (_super) {
  38306. __extends(PBRBaseMaterial, _super);
  38307. /**
  38308. * Instantiates a new PBRMaterial instance.
  38309. *
  38310. * @param name The material name
  38311. * @param scene The scene the material will be use in.
  38312. */
  38313. function PBRBaseMaterial(name, scene) {
  38314. var _this = _super.call(this, name, scene) || this;
  38315. /**
  38316. * Intensity of the direct lights e.g. the four lights available in your scene.
  38317. * This impacts both the direct diffuse and specular highlights.
  38318. */
  38319. _this._directIntensity = 1.0;
  38320. /**
  38321. * Intensity of the emissive part of the material.
  38322. * This helps controlling the emissive effect without modifying the emissive color.
  38323. */
  38324. _this._emissiveIntensity = 1.0;
  38325. /**
  38326. * Intensity of the environment e.g. how much the environment will light the object
  38327. * either through harmonics for rough material or through the refelction for shiny ones.
  38328. */
  38329. _this._environmentIntensity = 1.0;
  38330. /**
  38331. * This is a special control allowing the reduction of the specular highlights coming from the
  38332. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38333. */
  38334. _this._specularIntensity = 1.0;
  38335. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38336. /**
  38337. * Debug Control allowing disabling the bump map on this material.
  38338. */
  38339. _this._disableBumpMap = false;
  38340. /**
  38341. * AKA Occlusion Texture Intensity in other nomenclature.
  38342. */
  38343. _this._ambientTextureStrength = 1.0;
  38344. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38345. /**
  38346. * AKA Diffuse Color in other nomenclature.
  38347. */
  38348. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38349. /**
  38350. * AKA Specular Color in other nomenclature.
  38351. */
  38352. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38353. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  38354. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38355. /**
  38356. * AKA Glossiness in other nomenclature.
  38357. */
  38358. _this._microSurface = 0.9;
  38359. /**
  38360. * source material index of refraction (IOR)' / 'destination material IOR.
  38361. */
  38362. _this._indexOfRefraction = 0.66;
  38363. /**
  38364. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38365. */
  38366. _this._invertRefractionY = false;
  38367. /**
  38368. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38369. * Materials half opaque for instance using refraction could benefit from this control.
  38370. */
  38371. _this._linkRefractionWithTransparency = false;
  38372. _this._useLightmapAsShadowmap = false;
  38373. /**
  38374. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38375. * makes the reflect vector face the model (under horizon).
  38376. */
  38377. _this._useHorizonOcclusion = true;
  38378. /**
  38379. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38380. * too much the area relying on ambient texture to define their ambient occlusion.
  38381. */
  38382. _this._useRadianceOcclusion = true;
  38383. /**
  38384. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38385. */
  38386. _this._useAlphaFromAlbedoTexture = false;
  38387. /**
  38388. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38389. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38390. */
  38391. _this._useSpecularOverAlpha = true;
  38392. /**
  38393. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38394. */
  38395. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38396. /**
  38397. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38398. */
  38399. _this._useRoughnessFromMetallicTextureAlpha = true;
  38400. /**
  38401. * Specifies if the metallic texture contains the roughness information in its green channel.
  38402. */
  38403. _this._useRoughnessFromMetallicTextureGreen = false;
  38404. /**
  38405. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38406. */
  38407. _this._useMetallnessFromMetallicTextureBlue = false;
  38408. /**
  38409. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38410. */
  38411. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38412. /**
  38413. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38414. */
  38415. _this._useAmbientInGrayScale = false;
  38416. /**
  38417. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38418. * The material will try to infer what glossiness each pixel should be.
  38419. */
  38420. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38421. /**
  38422. * BJS is using an harcoded light falloff based on a manually sets up range.
  38423. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38424. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38425. */
  38426. _this._usePhysicalLightFalloff = true;
  38427. /**
  38428. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38429. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38430. */
  38431. _this._useRadianceOverAlpha = true;
  38432. /**
  38433. * Allows using the bump map in parallax mode.
  38434. */
  38435. _this._useParallax = false;
  38436. /**
  38437. * Allows using the bump map in parallax occlusion mode.
  38438. */
  38439. _this._useParallaxOcclusion = false;
  38440. /**
  38441. * Controls the scale bias of the parallax mode.
  38442. */
  38443. _this._parallaxScaleBias = 0.05;
  38444. /**
  38445. * If sets to true, disables all the lights affecting the material.
  38446. */
  38447. _this._disableLighting = false;
  38448. /**
  38449. * Number of Simultaneous lights allowed on the material.
  38450. */
  38451. _this._maxSimultaneousLights = 4;
  38452. /**
  38453. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  38454. */
  38455. _this._invertNormalMapX = false;
  38456. /**
  38457. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  38458. */
  38459. _this._invertNormalMapY = false;
  38460. /**
  38461. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38462. */
  38463. _this._twoSidedLighting = false;
  38464. /**
  38465. * Defines the alpha limits in alpha test mode.
  38466. */
  38467. _this._alphaCutOff = 0.4;
  38468. /**
  38469. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38470. */
  38471. _this._forceAlphaTest = false;
  38472. /**
  38473. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38474. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38475. */
  38476. _this._useAlphaFresnel = false;
  38477. /**
  38478. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38479. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38480. */
  38481. _this._useLinearAlphaFresnel = false;
  38482. /**
  38483. * The transparency mode of the material.
  38484. */
  38485. _this._transparencyMode = null;
  38486. /**
  38487. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  38488. * from cos thetav and roughness:
  38489. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  38490. */
  38491. _this._environmentBRDFTexture = null;
  38492. /**
  38493. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38494. */
  38495. _this._forceIrradianceInFragment = false;
  38496. /**
  38497. * Force normal to face away from face.
  38498. */
  38499. _this._forceNormalForward = false;
  38500. /**
  38501. * Force metallic workflow.
  38502. */
  38503. _this._forceMetallicWorkflow = false;
  38504. _this._renderTargets = new BABYLON.SmartArray(16);
  38505. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38506. // Setup the default processing configuration to the scene.
  38507. _this._attachImageProcessingConfiguration(null);
  38508. _this.getRenderTargetTextures = function () {
  38509. _this._renderTargets.reset();
  38510. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38511. _this._renderTargets.push(_this._reflectionTexture);
  38512. }
  38513. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38514. _this._renderTargets.push(_this._refractionTexture);
  38515. }
  38516. return _this._renderTargets;
  38517. };
  38518. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38519. return _this;
  38520. }
  38521. /**
  38522. * Attaches a new image processing configuration to the PBR Material.
  38523. * @param configuration
  38524. */
  38525. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38526. var _this = this;
  38527. if (configuration === this._imageProcessingConfiguration) {
  38528. return;
  38529. }
  38530. // Detaches observer.
  38531. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38532. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38533. }
  38534. // Pick the scene configuration if needed.
  38535. if (!configuration) {
  38536. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38537. }
  38538. else {
  38539. this._imageProcessingConfiguration = configuration;
  38540. }
  38541. // Attaches observer.
  38542. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38543. _this._markAllSubMeshesAsImageProcessingDirty();
  38544. });
  38545. };
  38546. PBRBaseMaterial.prototype.getClassName = function () {
  38547. return "PBRBaseMaterial";
  38548. };
  38549. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38550. get: function () {
  38551. return this._useLogarithmicDepth;
  38552. },
  38553. set: function (value) {
  38554. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38555. },
  38556. enumerable: true,
  38557. configurable: true
  38558. });
  38559. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38560. /**
  38561. * Gets the current transparency mode.
  38562. */
  38563. get: function () {
  38564. return this._transparencyMode;
  38565. },
  38566. /**
  38567. * Sets the transparency mode of the material.
  38568. */
  38569. set: function (value) {
  38570. if (this._transparencyMode === value) {
  38571. return;
  38572. }
  38573. this._transparencyMode = value;
  38574. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38575. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38576. },
  38577. enumerable: true,
  38578. configurable: true
  38579. });
  38580. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38581. /**
  38582. * Returns true if alpha blending should be disabled.
  38583. */
  38584. get: function () {
  38585. return (this._linkRefractionWithTransparency ||
  38586. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38587. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38588. },
  38589. enumerable: true,
  38590. configurable: true
  38591. });
  38592. /**
  38593. * Specifies whether or not this material should be rendered in alpha blend mode.
  38594. */
  38595. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38596. if (this._disableAlphaBlending) {
  38597. return false;
  38598. }
  38599. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38600. };
  38601. /**
  38602. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38603. */
  38604. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38605. if (this._disableAlphaBlending) {
  38606. return false;
  38607. }
  38608. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38609. };
  38610. /**
  38611. * Specifies whether or not this material should be rendered in alpha test mode.
  38612. */
  38613. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38614. if (this._forceAlphaTest) {
  38615. return true;
  38616. }
  38617. if (this._linkRefractionWithTransparency) {
  38618. return false;
  38619. }
  38620. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38621. };
  38622. /**
  38623. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38624. */
  38625. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38626. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38627. };
  38628. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38629. return this._albedoTexture;
  38630. };
  38631. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38632. var _this = this;
  38633. if (subMesh.effect && this.isFrozen) {
  38634. if (this._wasPreviouslyReady) {
  38635. return true;
  38636. }
  38637. }
  38638. if (!subMesh._materialDefines) {
  38639. subMesh._materialDefines = new PBRMaterialDefines();
  38640. }
  38641. var scene = this.getScene();
  38642. var defines = subMesh._materialDefines;
  38643. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38644. if (defines._renderId === scene.getRenderId()) {
  38645. return true;
  38646. }
  38647. }
  38648. var engine = scene.getEngine();
  38649. // Lights
  38650. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38651. defines._needNormals = true;
  38652. // Textures
  38653. if (defines._areTexturesDirty) {
  38654. defines._needUVs = false;
  38655. if (scene.texturesEnabled) {
  38656. if (scene.getEngine().getCaps().textureLOD) {
  38657. defines.LODBASEDMICROSFURACE = true;
  38658. }
  38659. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38660. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38661. return false;
  38662. }
  38663. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38664. }
  38665. else {
  38666. defines.ALBEDO = false;
  38667. }
  38668. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38669. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38670. return false;
  38671. }
  38672. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38673. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38674. }
  38675. else {
  38676. defines.AMBIENT = false;
  38677. }
  38678. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38679. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38680. return false;
  38681. }
  38682. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38683. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38684. }
  38685. else {
  38686. defines.OPACITY = false;
  38687. }
  38688. var reflectionTexture = this._getReflectionTexture();
  38689. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38690. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38691. return false;
  38692. }
  38693. defines.REFLECTION = true;
  38694. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38695. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38696. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38697. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38698. defines.INVERTCUBICMAP = true;
  38699. }
  38700. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38701. switch (reflectionTexture.coordinatesMode) {
  38702. case BABYLON.Texture.CUBIC_MODE:
  38703. case BABYLON.Texture.INVCUBIC_MODE:
  38704. defines.REFLECTIONMAP_CUBIC = true;
  38705. break;
  38706. case BABYLON.Texture.EXPLICIT_MODE:
  38707. defines.REFLECTIONMAP_EXPLICIT = true;
  38708. break;
  38709. case BABYLON.Texture.PLANAR_MODE:
  38710. defines.REFLECTIONMAP_PLANAR = true;
  38711. break;
  38712. case BABYLON.Texture.PROJECTION_MODE:
  38713. defines.REFLECTIONMAP_PROJECTION = true;
  38714. break;
  38715. case BABYLON.Texture.SKYBOX_MODE:
  38716. defines.REFLECTIONMAP_SKYBOX = true;
  38717. break;
  38718. case BABYLON.Texture.SPHERICAL_MODE:
  38719. defines.REFLECTIONMAP_SPHERICAL = true;
  38720. break;
  38721. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38722. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38723. break;
  38724. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38725. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38726. break;
  38727. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38728. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38729. break;
  38730. }
  38731. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38732. if (reflectionTexture.sphericalPolynomial) {
  38733. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38734. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38735. defines.USESPHERICALINVERTEX = false;
  38736. }
  38737. else {
  38738. defines.USESPHERICALINVERTEX = true;
  38739. }
  38740. }
  38741. }
  38742. }
  38743. else {
  38744. defines.REFLECTION = false;
  38745. defines.REFLECTIONMAP_3D = false;
  38746. defines.REFLECTIONMAP_SPHERICAL = false;
  38747. defines.REFLECTIONMAP_PLANAR = false;
  38748. defines.REFLECTIONMAP_CUBIC = false;
  38749. defines.REFLECTIONMAP_PROJECTION = false;
  38750. defines.REFLECTIONMAP_SKYBOX = false;
  38751. defines.REFLECTIONMAP_EXPLICIT = false;
  38752. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38753. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38754. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38755. defines.INVERTCUBICMAP = false;
  38756. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38757. defines.USESPHERICALINVERTEX = false;
  38758. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38759. defines.LODINREFLECTIONALPHA = false;
  38760. defines.GAMMAREFLECTION = false;
  38761. }
  38762. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38763. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38764. return false;
  38765. }
  38766. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38767. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38768. }
  38769. else {
  38770. defines.LIGHTMAP = false;
  38771. }
  38772. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38773. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38774. return false;
  38775. }
  38776. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38777. }
  38778. else {
  38779. defines.EMISSIVE = false;
  38780. }
  38781. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38782. if (this._metallicTexture) {
  38783. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38784. return false;
  38785. }
  38786. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38787. defines.METALLICWORKFLOW = true;
  38788. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38789. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38790. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38791. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38792. }
  38793. else if (this._reflectivityTexture) {
  38794. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38795. return false;
  38796. }
  38797. defines.METALLICWORKFLOW = false;
  38798. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38799. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38800. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38801. }
  38802. else {
  38803. defines.METALLICWORKFLOW = false;
  38804. defines.REFLECTIVITY = false;
  38805. }
  38806. if (this._microSurfaceTexture) {
  38807. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38808. return false;
  38809. }
  38810. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38811. }
  38812. else {
  38813. defines.MICROSURFACEMAP = false;
  38814. }
  38815. }
  38816. else {
  38817. defines.REFLECTIVITY = false;
  38818. defines.MICROSURFACEMAP = false;
  38819. }
  38820. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38821. // Bump texure can not be none blocking.
  38822. if (!this._bumpTexture.isReady()) {
  38823. return false;
  38824. }
  38825. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38826. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38827. defines.PARALLAX = true;
  38828. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38829. }
  38830. else {
  38831. defines.PARALLAX = false;
  38832. }
  38833. }
  38834. else {
  38835. defines.BUMP = false;
  38836. }
  38837. var refractionTexture = this._getRefractionTexture();
  38838. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38839. if (!refractionTexture.isReadyOrNotBlocking()) {
  38840. return false;
  38841. }
  38842. defines.REFRACTION = true;
  38843. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38844. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38845. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38846. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38847. if (this._linkRefractionWithTransparency) {
  38848. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38849. }
  38850. }
  38851. else {
  38852. defines.REFRACTION = false;
  38853. }
  38854. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38855. // This is blocking.
  38856. if (!this._environmentBRDFTexture.isReady()) {
  38857. return false;
  38858. }
  38859. defines.ENVIRONMENTBRDF = true;
  38860. }
  38861. else {
  38862. defines.ENVIRONMENTBRDF = false;
  38863. }
  38864. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38865. defines.ALPHAFROMALBEDO = true;
  38866. }
  38867. else {
  38868. defines.ALPHAFROMALBEDO = false;
  38869. }
  38870. }
  38871. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38872. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38873. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38874. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38875. defines.METALLICWORKFLOW = true;
  38876. }
  38877. else {
  38878. defines.METALLICWORKFLOW = false;
  38879. }
  38880. if (!this.backFaceCulling && this._twoSidedLighting) {
  38881. defines.TWOSIDEDLIGHTING = true;
  38882. }
  38883. else {
  38884. defines.TWOSIDEDLIGHTING = false;
  38885. }
  38886. defines.ALPHATESTVALUE = this._alphaCutOff;
  38887. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38888. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38889. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38890. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38891. }
  38892. if (defines._areImageProcessingDirty) {
  38893. if (!this._imageProcessingConfiguration.isReady()) {
  38894. return false;
  38895. }
  38896. this._imageProcessingConfiguration.prepareDefines(defines);
  38897. }
  38898. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38899. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38900. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38901. // Misc.
  38902. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  38903. // Values that need to be evaluated on every frame
  38904. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  38905. // Attribs
  38906. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38907. var bufferMesh = null;
  38908. if (mesh instanceof BABYLON.InstancedMesh) {
  38909. bufferMesh = mesh.sourceMesh;
  38910. }
  38911. else if (mesh instanceof BABYLON.Mesh) {
  38912. bufferMesh = mesh;
  38913. }
  38914. if (bufferMesh) {
  38915. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38916. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38917. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38918. var normals = normalVertexBuffer.getData();
  38919. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38920. var strideSize = normalVertexBuffer.getStrideSize();
  38921. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38922. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38923. defines.NORMAL = false;
  38924. }
  38925. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38926. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38927. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38928. var tangents = tangentVertexBuffer.getData();
  38929. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38930. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38931. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38932. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38933. defines.TANGENT = false;
  38934. }
  38935. }
  38936. }
  38937. else {
  38938. if (!scene.getEngine().getCaps().standardDerivatives) {
  38939. bufferMesh.createNormals(true);
  38940. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38941. }
  38942. }
  38943. }
  38944. }
  38945. // Get correct effect
  38946. if (defines.isDirty) {
  38947. defines.markAsProcessed();
  38948. scene.resetCachedMaterial();
  38949. // Fallbacks
  38950. var fallbacks = new BABYLON.EffectFallbacks();
  38951. var fallbackRank = 0;
  38952. if (defines.USESPHERICALINVERTEX) {
  38953. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38954. }
  38955. if (defines.FOG) {
  38956. fallbacks.addFallback(fallbackRank, "FOG");
  38957. }
  38958. if (defines.POINTSIZE) {
  38959. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38960. }
  38961. if (defines.LOGARITHMICDEPTH) {
  38962. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38963. }
  38964. if (defines.PARALLAX) {
  38965. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38966. }
  38967. if (defines.PARALLAXOCCLUSION) {
  38968. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38969. }
  38970. if (defines.ENVIRONMENTBRDF) {
  38971. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38972. }
  38973. if (defines.TANGENT) {
  38974. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38975. }
  38976. if (defines.BUMP) {
  38977. fallbacks.addFallback(fallbackRank++, "BUMP");
  38978. }
  38979. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38980. if (defines.SPECULARTERM) {
  38981. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38982. }
  38983. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38984. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38985. }
  38986. if (defines.LIGHTMAP) {
  38987. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38988. }
  38989. if (defines.NORMAL) {
  38990. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38991. }
  38992. if (defines.AMBIENT) {
  38993. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38994. }
  38995. if (defines.EMISSIVE) {
  38996. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38997. }
  38998. if (defines.VERTEXCOLOR) {
  38999. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  39000. }
  39001. if (defines.NUM_BONE_INFLUENCERS > 0) {
  39002. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  39003. }
  39004. if (defines.MORPHTARGETS) {
  39005. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  39006. }
  39007. //Attributes
  39008. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39009. if (defines.NORMAL) {
  39010. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39011. }
  39012. if (defines.TANGENT) {
  39013. attribs.push(BABYLON.VertexBuffer.TangentKind);
  39014. }
  39015. if (defines.UV1) {
  39016. attribs.push(BABYLON.VertexBuffer.UVKind);
  39017. }
  39018. if (defines.UV2) {
  39019. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39020. }
  39021. if (defines.VERTEXCOLOR) {
  39022. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39023. }
  39024. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39025. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39026. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39027. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  39028. "vFogInfos", "vFogColor", "pointSize",
  39029. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39030. "mBones",
  39031. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  39032. "vLightingIntensity",
  39033. "logarithmicDepthConstant",
  39034. "vSphericalX", "vSphericalY", "vSphericalZ",
  39035. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  39036. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  39037. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  39038. "vTangentSpaceParams"
  39039. ];
  39040. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  39041. "bumpSampler", "lightmapSampler", "opacitySampler",
  39042. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  39043. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  39044. "microSurfaceSampler", "environmentBrdfSampler"];
  39045. var uniformBuffers = ["Material", "Scene"];
  39046. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39047. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39048. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39049. uniformsNames: uniforms,
  39050. uniformBuffersNames: uniformBuffers,
  39051. samplers: samplers,
  39052. defines: defines,
  39053. maxSimultaneousLights: this._maxSimultaneousLights
  39054. });
  39055. var onCompiled = function (effect) {
  39056. if (_this.onCompiled) {
  39057. _this.onCompiled(effect);
  39058. }
  39059. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  39060. };
  39061. var join = defines.toString();
  39062. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  39063. attributes: attribs,
  39064. uniformsNames: uniforms,
  39065. uniformBuffersNames: uniformBuffers,
  39066. samplers: samplers,
  39067. defines: join,
  39068. fallbacks: fallbacks,
  39069. onCompiled: onCompiled,
  39070. onError: this.onError,
  39071. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39072. }, engine), defines);
  39073. this.buildUniformLayout();
  39074. }
  39075. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39076. return false;
  39077. }
  39078. defines._renderId = scene.getRenderId();
  39079. this._wasPreviouslyReady = true;
  39080. return true;
  39081. };
  39082. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  39083. // Order is important !
  39084. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  39085. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  39086. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39087. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39088. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39089. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  39090. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  39091. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39092. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39093. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39094. this._uniformBuffer.addUniform("albedoMatrix", 16);
  39095. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39096. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39097. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39098. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39099. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  39100. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  39101. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39102. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39103. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39104. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39105. this._uniformBuffer.addUniform("vReflectionColor", 3);
  39106. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  39107. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  39108. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  39109. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  39110. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  39111. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39112. this._uniformBuffer.addUniform("pointSize", 1);
  39113. this._uniformBuffer.create();
  39114. };
  39115. PBRBaseMaterial.prototype.unbind = function () {
  39116. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39117. this._uniformBuffer.setTexture("reflectionSampler", null);
  39118. }
  39119. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39120. this._uniformBuffer.setTexture("refractionSampler", null);
  39121. }
  39122. _super.prototype.unbind.call(this);
  39123. };
  39124. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39125. this._activeEffect.setMatrix("world", world);
  39126. };
  39127. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39128. var scene = this.getScene();
  39129. var defines = subMesh._materialDefines;
  39130. if (!defines) {
  39131. return;
  39132. }
  39133. var effect = subMesh.effect;
  39134. if (!effect) {
  39135. return;
  39136. }
  39137. this._activeEffect = effect;
  39138. // Matrices
  39139. this.bindOnlyWorldMatrix(world);
  39140. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39141. // Bones
  39142. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  39143. var reflectionTexture = null;
  39144. if (mustRebind) {
  39145. this._uniformBuffer.bindToEffect(effect, "Material");
  39146. this.bindViewProjection(effect);
  39147. reflectionTexture = this._getReflectionTexture();
  39148. var refractionTexture = this._getRefractionTexture();
  39149. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39150. // Texture uniforms
  39151. if (scene.texturesEnabled) {
  39152. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39153. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39154. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  39155. }
  39156. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39157. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39158. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39159. }
  39160. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39161. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39162. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39163. }
  39164. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39165. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39166. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39167. var polynomials = reflectionTexture.sphericalPolynomial;
  39168. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  39169. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  39170. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  39171. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  39172. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  39173. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  39174. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  39175. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  39176. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  39177. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  39178. }
  39179. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  39180. }
  39181. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39182. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39183. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39184. }
  39185. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39186. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39187. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39188. }
  39189. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39190. if (this._metallicTexture) {
  39191. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39192. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  39193. }
  39194. else if (this._reflectivityTexture) {
  39195. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39196. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  39197. }
  39198. if (this._microSurfaceTexture) {
  39199. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39200. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  39201. }
  39202. }
  39203. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39204. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39205. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39206. if (scene._mirroredCameraPosition) {
  39207. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39208. }
  39209. else {
  39210. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39211. }
  39212. }
  39213. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39214. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  39215. var depth = 1.0;
  39216. if (!refractionTexture.isCube) {
  39217. if (refractionTexture.depth) {
  39218. depth = refractionTexture.depth;
  39219. }
  39220. }
  39221. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39222. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  39223. }
  39224. }
  39225. // Point size
  39226. if (this.pointsCloud) {
  39227. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39228. }
  39229. // Colors
  39230. if (defines.METALLICWORKFLOW) {
  39231. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39232. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39233. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39234. }
  39235. else {
  39236. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  39237. }
  39238. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  39239. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  39240. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  39241. // Misc
  39242. this._lightingInfos.x = this._directIntensity;
  39243. this._lightingInfos.y = this._emissiveIntensity;
  39244. this._lightingInfos.z = this._environmentIntensity;
  39245. this._lightingInfos.w = this._specularIntensity;
  39246. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39247. }
  39248. // Textures
  39249. if (scene.texturesEnabled) {
  39250. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39251. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39252. }
  39253. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39254. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39255. }
  39256. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39257. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39258. }
  39259. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39260. if (defines.LODBASEDMICROSFURACE) {
  39261. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  39262. }
  39263. else {
  39264. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  39265. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  39266. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  39267. }
  39268. }
  39269. if (defines.ENVIRONMENTBRDF) {
  39270. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  39271. }
  39272. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39273. if (defines.LODBASEDMICROSFURACE) {
  39274. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  39275. }
  39276. else {
  39277. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  39278. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  39279. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  39280. }
  39281. }
  39282. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39283. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39284. }
  39285. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39286. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39287. }
  39288. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39289. if (this._metallicTexture) {
  39290. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39291. }
  39292. else if (this._reflectivityTexture) {
  39293. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39294. }
  39295. if (this._microSurfaceTexture) {
  39296. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39297. }
  39298. }
  39299. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39300. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39301. }
  39302. }
  39303. // Clip plane
  39304. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39305. // Colors
  39306. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39307. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39308. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  39309. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  39310. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39311. }
  39312. if (mustRebind || !this.isFrozen) {
  39313. // Lights
  39314. if (scene.lightsEnabled && !this._disableLighting) {
  39315. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39316. }
  39317. // View
  39318. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39319. this.bindView(effect);
  39320. }
  39321. // Fog
  39322. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39323. // Morph targets
  39324. if (defines.NUM_MORPH_INFLUENCERS) {
  39325. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39326. }
  39327. // image processing
  39328. this._imageProcessingConfiguration.bind(this._activeEffect);
  39329. // Log. depth
  39330. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39331. }
  39332. this._uniformBuffer.update();
  39333. this._afterBind(mesh);
  39334. };
  39335. PBRBaseMaterial.prototype.getAnimatables = function () {
  39336. var results = [];
  39337. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39338. results.push(this._albedoTexture);
  39339. }
  39340. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39341. results.push(this._ambientTexture);
  39342. }
  39343. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39344. results.push(this._opacityTexture);
  39345. }
  39346. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39347. results.push(this._reflectionTexture);
  39348. }
  39349. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39350. results.push(this._emissiveTexture);
  39351. }
  39352. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39353. results.push(this._metallicTexture);
  39354. }
  39355. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39356. results.push(this._reflectivityTexture);
  39357. }
  39358. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39359. results.push(this._bumpTexture);
  39360. }
  39361. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39362. results.push(this._lightmapTexture);
  39363. }
  39364. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39365. results.push(this._refractionTexture);
  39366. }
  39367. return results;
  39368. };
  39369. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  39370. if (this._reflectionTexture) {
  39371. return this._reflectionTexture;
  39372. }
  39373. return this.getScene().environmentTexture;
  39374. };
  39375. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  39376. if (this._refractionTexture) {
  39377. return this._refractionTexture;
  39378. }
  39379. if (this._linkRefractionWithTransparency) {
  39380. return this.getScene().environmentTexture;
  39381. }
  39382. return null;
  39383. };
  39384. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39385. if (forceDisposeTextures) {
  39386. if (this._albedoTexture) {
  39387. this._albedoTexture.dispose();
  39388. }
  39389. if (this._ambientTexture) {
  39390. this._ambientTexture.dispose();
  39391. }
  39392. if (this._opacityTexture) {
  39393. this._opacityTexture.dispose();
  39394. }
  39395. if (this._reflectionTexture) {
  39396. this._reflectionTexture.dispose();
  39397. }
  39398. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  39399. this._environmentBRDFTexture.dispose();
  39400. }
  39401. if (this._emissiveTexture) {
  39402. this._emissiveTexture.dispose();
  39403. }
  39404. if (this._metallicTexture) {
  39405. this._metallicTexture.dispose();
  39406. }
  39407. if (this._reflectivityTexture) {
  39408. this._reflectivityTexture.dispose();
  39409. }
  39410. if (this._bumpTexture) {
  39411. this._bumpTexture.dispose();
  39412. }
  39413. if (this._lightmapTexture) {
  39414. this._lightmapTexture.dispose();
  39415. }
  39416. if (this._refractionTexture) {
  39417. this._refractionTexture.dispose();
  39418. }
  39419. }
  39420. this._renderTargets.dispose();
  39421. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39422. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39423. }
  39424. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39425. };
  39426. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39427. __decorate([
  39428. BABYLON.serializeAsImageProcessingConfiguration()
  39429. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  39430. __decorate([
  39431. BABYLON.serialize()
  39432. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39433. __decorate([
  39434. BABYLON.serialize()
  39435. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  39436. return PBRBaseMaterial;
  39437. }(BABYLON.PushMaterial));
  39438. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39439. })(BABYLON || (BABYLON = {}));
  39440. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39441. var BABYLON;
  39442. (function (BABYLON) {
  39443. /**
  39444. * The Physically based simple base material of BJS.
  39445. *
  39446. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39447. * It is used as the base class for both the specGloss and metalRough conventions.
  39448. */
  39449. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  39450. __extends(PBRBaseSimpleMaterial, _super);
  39451. /**
  39452. * Instantiates a new PBRMaterial instance.
  39453. *
  39454. * @param name The material name
  39455. * @param scene The scene the material will be use in.
  39456. */
  39457. function PBRBaseSimpleMaterial(name, scene) {
  39458. var _this = _super.call(this, name, scene) || this;
  39459. /**
  39460. * Number of Simultaneous lights allowed on the material.
  39461. */
  39462. _this.maxSimultaneousLights = 4;
  39463. /**
  39464. * If sets to true, disables all the lights affecting the material.
  39465. */
  39466. _this.disableLighting = false;
  39467. /**
  39468. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39469. */
  39470. _this.invertNormalMapX = false;
  39471. /**
  39472. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39473. */
  39474. _this.invertNormalMapY = false;
  39475. /**
  39476. * Emissivie color used to self-illuminate the model.
  39477. */
  39478. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39479. /**
  39480. * Occlusion Channel Strenght.
  39481. */
  39482. _this.occlusionStrength = 1.0;
  39483. _this.useLightmapAsShadowmap = false;
  39484. _this._useAlphaFromAlbedoTexture = true;
  39485. _this._useAmbientInGrayScale = true;
  39486. return _this;
  39487. }
  39488. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39489. /**
  39490. * Gets the current double sided mode.
  39491. */
  39492. get: function () {
  39493. return this._twoSidedLighting;
  39494. },
  39495. /**
  39496. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39497. */
  39498. set: function (value) {
  39499. if (this._twoSidedLighting === value) {
  39500. return;
  39501. }
  39502. this._twoSidedLighting = value;
  39503. this.backFaceCulling = !value;
  39504. this._markAllSubMeshesAsTexturesDirty();
  39505. },
  39506. enumerable: true,
  39507. configurable: true
  39508. });
  39509. /**
  39510. * Return the active textures of the material.
  39511. */
  39512. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  39513. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39514. if (this.environmentTexture) {
  39515. activeTextures.push(this.environmentTexture);
  39516. }
  39517. if (this.normalTexture) {
  39518. activeTextures.push(this.normalTexture);
  39519. }
  39520. if (this.emissiveTexture) {
  39521. activeTextures.push(this.emissiveTexture);
  39522. }
  39523. if (this.occlusionTexture) {
  39524. activeTextures.push(this.occlusionTexture);
  39525. }
  39526. if (this.lightmapTexture) {
  39527. activeTextures.push(this.lightmapTexture);
  39528. }
  39529. return activeTextures;
  39530. };
  39531. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39532. if (_super.prototype.hasTexture.call(this, texture)) {
  39533. return true;
  39534. }
  39535. if (this.lightmapTexture === texture) {
  39536. return true;
  39537. }
  39538. return false;
  39539. };
  39540. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39541. return "PBRBaseSimpleMaterial";
  39542. };
  39543. __decorate([
  39544. BABYLON.serialize(),
  39545. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39546. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39547. __decorate([
  39548. BABYLON.serialize(),
  39549. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39550. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39551. __decorate([
  39552. BABYLON.serializeAsTexture(),
  39553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39554. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39555. __decorate([
  39556. BABYLON.serialize(),
  39557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39558. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39559. __decorate([
  39560. BABYLON.serialize(),
  39561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39562. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39563. __decorate([
  39564. BABYLON.serializeAsTexture(),
  39565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39566. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39567. __decorate([
  39568. BABYLON.serializeAsColor3("emissive"),
  39569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39570. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39571. __decorate([
  39572. BABYLON.serializeAsTexture(),
  39573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39574. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39575. __decorate([
  39576. BABYLON.serialize(),
  39577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39578. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39579. __decorate([
  39580. BABYLON.serializeAsTexture(),
  39581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39582. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39583. __decorate([
  39584. BABYLON.serialize(),
  39585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39586. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39587. __decorate([
  39588. BABYLON.serialize()
  39589. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39590. __decorate([
  39591. BABYLON.serializeAsTexture(),
  39592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39593. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39594. __decorate([
  39595. BABYLON.serialize(),
  39596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39597. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39598. return PBRBaseSimpleMaterial;
  39599. }(BABYLON.PBRBaseMaterial));
  39600. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39601. })(BABYLON || (BABYLON = {}));
  39602. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39603. var BABYLON;
  39604. (function (BABYLON) {
  39605. /**
  39606. * The Physically based material of BJS.
  39607. *
  39608. * This offers the main features of a standard PBR material.
  39609. * For more information, please refer to the documentation :
  39610. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39611. */
  39612. var PBRMaterial = /** @class */ (function (_super) {
  39613. __extends(PBRMaterial, _super);
  39614. /**
  39615. * Instantiates a new PBRMaterial instance.
  39616. *
  39617. * @param name The material name
  39618. * @param scene The scene the material will be use in.
  39619. */
  39620. function PBRMaterial(name, scene) {
  39621. var _this = _super.call(this, name, scene) || this;
  39622. /**
  39623. * Intensity of the direct lights e.g. the four lights available in your scene.
  39624. * This impacts both the direct diffuse and specular highlights.
  39625. */
  39626. _this.directIntensity = 1.0;
  39627. /**
  39628. * Intensity of the emissive part of the material.
  39629. * This helps controlling the emissive effect without modifying the emissive color.
  39630. */
  39631. _this.emissiveIntensity = 1.0;
  39632. /**
  39633. * Intensity of the environment e.g. how much the environment will light the object
  39634. * either through harmonics for rough material or through the refelction for shiny ones.
  39635. */
  39636. _this.environmentIntensity = 1.0;
  39637. /**
  39638. * This is a special control allowing the reduction of the specular highlights coming from the
  39639. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39640. */
  39641. _this.specularIntensity = 1.0;
  39642. /**
  39643. * Debug Control allowing disabling the bump map on this material.
  39644. */
  39645. _this.disableBumpMap = false;
  39646. /**
  39647. * AKA Occlusion Texture Intensity in other nomenclature.
  39648. */
  39649. _this.ambientTextureStrength = 1.0;
  39650. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39651. /**
  39652. * AKA Diffuse Color in other nomenclature.
  39653. */
  39654. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39655. /**
  39656. * AKA Specular Color in other nomenclature.
  39657. */
  39658. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39659. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39660. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39661. /**
  39662. * AKA Glossiness in other nomenclature.
  39663. */
  39664. _this.microSurface = 1.0;
  39665. /**
  39666. * source material index of refraction (IOR)' / 'destination material IOR.
  39667. */
  39668. _this.indexOfRefraction = 0.66;
  39669. /**
  39670. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39671. */
  39672. _this.invertRefractionY = false;
  39673. /**
  39674. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39675. * Materials half opaque for instance using refraction could benefit from this control.
  39676. */
  39677. _this.linkRefractionWithTransparency = false;
  39678. _this.useLightmapAsShadowmap = false;
  39679. /**
  39680. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39681. */
  39682. _this.useAlphaFromAlbedoTexture = false;
  39683. /**
  39684. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39685. */
  39686. _this.forceAlphaTest = false;
  39687. /**
  39688. * Defines the alpha limits in alpha test mode.
  39689. */
  39690. _this.alphaCutOff = 0.4;
  39691. /**
  39692. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39693. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39694. */
  39695. _this.useSpecularOverAlpha = true;
  39696. /**
  39697. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39698. */
  39699. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39700. /**
  39701. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39702. */
  39703. _this.useRoughnessFromMetallicTextureAlpha = true;
  39704. /**
  39705. * Specifies if the metallic texture contains the roughness information in its green channel.
  39706. */
  39707. _this.useRoughnessFromMetallicTextureGreen = false;
  39708. /**
  39709. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39710. */
  39711. _this.useMetallnessFromMetallicTextureBlue = false;
  39712. /**
  39713. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39714. */
  39715. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39716. /**
  39717. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39718. */
  39719. _this.useAmbientInGrayScale = false;
  39720. /**
  39721. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39722. * The material will try to infer what glossiness each pixel should be.
  39723. */
  39724. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39725. /**
  39726. * BJS is using an harcoded light falloff based on a manually sets up range.
  39727. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39728. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39729. */
  39730. _this.usePhysicalLightFalloff = true;
  39731. /**
  39732. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39733. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39734. */
  39735. _this.useRadianceOverAlpha = true;
  39736. /**
  39737. * Allows using the bump map in parallax mode.
  39738. */
  39739. _this.useParallax = false;
  39740. /**
  39741. * Allows using the bump map in parallax occlusion mode.
  39742. */
  39743. _this.useParallaxOcclusion = false;
  39744. /**
  39745. * Controls the scale bias of the parallax mode.
  39746. */
  39747. _this.parallaxScaleBias = 0.05;
  39748. /**
  39749. * If sets to true, disables all the lights affecting the material.
  39750. */
  39751. _this.disableLighting = false;
  39752. /**
  39753. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39754. */
  39755. _this.forceIrradianceInFragment = false;
  39756. /**
  39757. * Number of Simultaneous lights allowed on the material.
  39758. */
  39759. _this.maxSimultaneousLights = 4;
  39760. /**
  39761. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39762. */
  39763. _this.invertNormalMapX = false;
  39764. /**
  39765. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39766. */
  39767. _this.invertNormalMapY = false;
  39768. /**
  39769. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39770. */
  39771. _this.twoSidedLighting = false;
  39772. /**
  39773. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39774. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39775. */
  39776. _this.useAlphaFresnel = false;
  39777. /**
  39778. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39779. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39780. */
  39781. _this.useLinearAlphaFresnel = false;
  39782. /**
  39783. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39784. * And/Or occlude the blended part.
  39785. */
  39786. _this.environmentBRDFTexture = null;
  39787. /**
  39788. * Force normal to face away from face.
  39789. */
  39790. _this.forceNormalForward = false;
  39791. /**
  39792. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39793. * makes the reflect vector face the model (under horizon).
  39794. */
  39795. _this.useHorizonOcclusion = true;
  39796. /**
  39797. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39798. * too much the area relying on ambient texture to define their ambient occlusion.
  39799. */
  39800. _this.useRadianceOcclusion = true;
  39801. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39802. return _this;
  39803. }
  39804. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39805. /**
  39806. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39807. */
  39808. get: function () {
  39809. return this._PBRMATERIAL_OPAQUE;
  39810. },
  39811. enumerable: true,
  39812. configurable: true
  39813. });
  39814. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39815. /**
  39816. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39817. */
  39818. get: function () {
  39819. return this._PBRMATERIAL_ALPHATEST;
  39820. },
  39821. enumerable: true,
  39822. configurable: true
  39823. });
  39824. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39825. /**
  39826. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39827. */
  39828. get: function () {
  39829. return this._PBRMATERIAL_ALPHABLEND;
  39830. },
  39831. enumerable: true,
  39832. configurable: true
  39833. });
  39834. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39835. /**
  39836. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39837. * They are also discarded below the alpha cutoff threshold to improve performances.
  39838. */
  39839. get: function () {
  39840. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39841. },
  39842. enumerable: true,
  39843. configurable: true
  39844. });
  39845. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39846. /**
  39847. * Gets the image processing configuration used either in this material.
  39848. */
  39849. get: function () {
  39850. return this._imageProcessingConfiguration;
  39851. },
  39852. /**
  39853. * Sets the Default image processing configuration used either in the this material.
  39854. *
  39855. * If sets to null, the scene one is in use.
  39856. */
  39857. set: function (value) {
  39858. this._attachImageProcessingConfiguration(value);
  39859. // Ensure the effect will be rebuilt.
  39860. this._markAllSubMeshesAsTexturesDirty();
  39861. },
  39862. enumerable: true,
  39863. configurable: true
  39864. });
  39865. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39866. /**
  39867. * Gets wether the color curves effect is enabled.
  39868. */
  39869. get: function () {
  39870. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39871. },
  39872. /**
  39873. * Sets wether the color curves effect is enabled.
  39874. */
  39875. set: function (value) {
  39876. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39877. },
  39878. enumerable: true,
  39879. configurable: true
  39880. });
  39881. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39882. /**
  39883. * Gets wether the color grading effect is enabled.
  39884. */
  39885. get: function () {
  39886. return this.imageProcessingConfiguration.colorGradingEnabled;
  39887. },
  39888. /**
  39889. * Gets wether the color grading effect is enabled.
  39890. */
  39891. set: function (value) {
  39892. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39893. },
  39894. enumerable: true,
  39895. configurable: true
  39896. });
  39897. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39898. /**
  39899. * Gets wether tonemapping is enabled or not.
  39900. */
  39901. get: function () {
  39902. return this._imageProcessingConfiguration.toneMappingEnabled;
  39903. },
  39904. /**
  39905. * Sets wether tonemapping is enabled or not
  39906. */
  39907. set: function (value) {
  39908. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39909. },
  39910. enumerable: true,
  39911. configurable: true
  39912. });
  39913. ;
  39914. ;
  39915. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39916. /**
  39917. * The camera exposure used on this material.
  39918. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39919. * This corresponds to a photographic exposure.
  39920. */
  39921. get: function () {
  39922. return this._imageProcessingConfiguration.exposure;
  39923. },
  39924. /**
  39925. * The camera exposure used on this material.
  39926. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39927. * This corresponds to a photographic exposure.
  39928. */
  39929. set: function (value) {
  39930. this._imageProcessingConfiguration.exposure = value;
  39931. },
  39932. enumerable: true,
  39933. configurable: true
  39934. });
  39935. ;
  39936. ;
  39937. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39938. /**
  39939. * Gets The camera contrast used on this material.
  39940. */
  39941. get: function () {
  39942. return this._imageProcessingConfiguration.contrast;
  39943. },
  39944. /**
  39945. * Sets The camera contrast used on this material.
  39946. */
  39947. set: function (value) {
  39948. this._imageProcessingConfiguration.contrast = value;
  39949. },
  39950. enumerable: true,
  39951. configurable: true
  39952. });
  39953. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39954. /**
  39955. * Gets the Color Grading 2D Lookup Texture.
  39956. */
  39957. get: function () {
  39958. return this._imageProcessingConfiguration.colorGradingTexture;
  39959. },
  39960. /**
  39961. * Sets the Color Grading 2D Lookup Texture.
  39962. */
  39963. set: function (value) {
  39964. this._imageProcessingConfiguration.colorGradingTexture = value;
  39965. },
  39966. enumerable: true,
  39967. configurable: true
  39968. });
  39969. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39970. /**
  39971. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39972. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39973. * 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;
  39974. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39975. */
  39976. get: function () {
  39977. return this._imageProcessingConfiguration.colorCurves;
  39978. },
  39979. /**
  39980. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39981. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39982. * 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;
  39983. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39984. */
  39985. set: function (value) {
  39986. this._imageProcessingConfiguration.colorCurves = value;
  39987. },
  39988. enumerable: true,
  39989. configurable: true
  39990. });
  39991. PBRMaterial.prototype.getClassName = function () {
  39992. return "PBRMaterial";
  39993. };
  39994. PBRMaterial.prototype.getActiveTextures = function () {
  39995. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39996. if (this._albedoTexture) {
  39997. activeTextures.push(this._albedoTexture);
  39998. }
  39999. if (this._ambientTexture) {
  40000. activeTextures.push(this._ambientTexture);
  40001. }
  40002. if (this._opacityTexture) {
  40003. activeTextures.push(this._opacityTexture);
  40004. }
  40005. if (this._reflectionTexture) {
  40006. activeTextures.push(this._reflectionTexture);
  40007. }
  40008. if (this._emissiveTexture) {
  40009. activeTextures.push(this._emissiveTexture);
  40010. }
  40011. if (this._reflectivityTexture) {
  40012. activeTextures.push(this._reflectivityTexture);
  40013. }
  40014. if (this._metallicTexture) {
  40015. activeTextures.push(this._metallicTexture);
  40016. }
  40017. if (this._microSurfaceTexture) {
  40018. activeTextures.push(this._microSurfaceTexture);
  40019. }
  40020. if (this._bumpTexture) {
  40021. activeTextures.push(this._bumpTexture);
  40022. }
  40023. if (this._lightmapTexture) {
  40024. activeTextures.push(this._lightmapTexture);
  40025. }
  40026. if (this._refractionTexture) {
  40027. activeTextures.push(this._refractionTexture);
  40028. }
  40029. return activeTextures;
  40030. };
  40031. PBRMaterial.prototype.hasTexture = function (texture) {
  40032. if (_super.prototype.hasTexture.call(this, texture)) {
  40033. return true;
  40034. }
  40035. if (this._albedoTexture === texture) {
  40036. return true;
  40037. }
  40038. if (this._ambientTexture === texture) {
  40039. return true;
  40040. }
  40041. if (this._opacityTexture === texture) {
  40042. return true;
  40043. }
  40044. if (this._reflectionTexture === texture) {
  40045. return true;
  40046. }
  40047. if (this._reflectivityTexture === texture) {
  40048. return true;
  40049. }
  40050. if (this._metallicTexture === texture) {
  40051. return true;
  40052. }
  40053. if (this._microSurfaceTexture === texture) {
  40054. return true;
  40055. }
  40056. if (this._bumpTexture === texture) {
  40057. return true;
  40058. }
  40059. if (this._lightmapTexture === texture) {
  40060. return true;
  40061. }
  40062. if (this._refractionTexture === texture) {
  40063. return true;
  40064. }
  40065. return false;
  40066. };
  40067. PBRMaterial.prototype.clone = function (name) {
  40068. var _this = this;
  40069. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  40070. clone.id = name;
  40071. clone.name = name;
  40072. return clone;
  40073. };
  40074. PBRMaterial.prototype.serialize = function () {
  40075. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40076. serializationObject.customType = "BABYLON.PBRMaterial";
  40077. return serializationObject;
  40078. };
  40079. // Statics
  40080. PBRMaterial.Parse = function (source, scene, rootUrl) {
  40081. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  40082. };
  40083. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  40084. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  40085. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  40086. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  40087. __decorate([
  40088. BABYLON.serialize(),
  40089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40090. ], PBRMaterial.prototype, "directIntensity", void 0);
  40091. __decorate([
  40092. BABYLON.serialize(),
  40093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40094. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  40095. __decorate([
  40096. BABYLON.serialize(),
  40097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40098. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  40099. __decorate([
  40100. BABYLON.serialize(),
  40101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40102. ], PBRMaterial.prototype, "specularIntensity", void 0);
  40103. __decorate([
  40104. BABYLON.serialize(),
  40105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40106. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  40107. __decorate([
  40108. BABYLON.serializeAsTexture(),
  40109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40110. ], PBRMaterial.prototype, "albedoTexture", void 0);
  40111. __decorate([
  40112. BABYLON.serializeAsTexture(),
  40113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40114. ], PBRMaterial.prototype, "ambientTexture", void 0);
  40115. __decorate([
  40116. BABYLON.serialize(),
  40117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40118. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  40119. __decorate([
  40120. BABYLON.serializeAsTexture(),
  40121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40122. ], PBRMaterial.prototype, "opacityTexture", void 0);
  40123. __decorate([
  40124. BABYLON.serializeAsTexture(),
  40125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40126. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  40127. __decorate([
  40128. BABYLON.serializeAsTexture(),
  40129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40130. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  40131. __decorate([
  40132. BABYLON.serializeAsTexture(),
  40133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40134. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  40135. __decorate([
  40136. BABYLON.serializeAsTexture(),
  40137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40138. ], PBRMaterial.prototype, "metallicTexture", void 0);
  40139. __decorate([
  40140. BABYLON.serialize(),
  40141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40142. ], PBRMaterial.prototype, "metallic", void 0);
  40143. __decorate([
  40144. BABYLON.serialize(),
  40145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40146. ], PBRMaterial.prototype, "roughness", void 0);
  40147. __decorate([
  40148. BABYLON.serializeAsTexture(),
  40149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40150. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  40151. __decorate([
  40152. BABYLON.serializeAsTexture(),
  40153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40154. ], PBRMaterial.prototype, "bumpTexture", void 0);
  40155. __decorate([
  40156. BABYLON.serializeAsTexture(),
  40157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  40158. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  40159. __decorate([
  40160. BABYLON.serializeAsTexture(),
  40161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40162. ], PBRMaterial.prototype, "refractionTexture", void 0);
  40163. __decorate([
  40164. BABYLON.serializeAsColor3("ambient"),
  40165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40166. ], PBRMaterial.prototype, "ambientColor", void 0);
  40167. __decorate([
  40168. BABYLON.serializeAsColor3("albedo"),
  40169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40170. ], PBRMaterial.prototype, "albedoColor", void 0);
  40171. __decorate([
  40172. BABYLON.serializeAsColor3("reflectivity"),
  40173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40174. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  40175. __decorate([
  40176. BABYLON.serializeAsColor3("reflection"),
  40177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40178. ], PBRMaterial.prototype, "reflectionColor", void 0);
  40179. __decorate([
  40180. BABYLON.serializeAsColor3("emissive"),
  40181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40182. ], PBRMaterial.prototype, "emissiveColor", void 0);
  40183. __decorate([
  40184. BABYLON.serialize(),
  40185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40186. ], PBRMaterial.prototype, "microSurface", void 0);
  40187. __decorate([
  40188. BABYLON.serialize(),
  40189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40190. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  40191. __decorate([
  40192. BABYLON.serialize(),
  40193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40194. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  40195. __decorate([
  40196. BABYLON.serialize(),
  40197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40198. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  40199. __decorate([
  40200. BABYLON.serialize(),
  40201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40202. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40203. __decorate([
  40204. BABYLON.serialize(),
  40205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40206. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  40207. __decorate([
  40208. BABYLON.serialize(),
  40209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40210. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  40211. __decorate([
  40212. BABYLON.serialize(),
  40213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40214. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  40215. __decorate([
  40216. BABYLON.serialize(),
  40217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40218. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  40219. __decorate([
  40220. BABYLON.serialize(),
  40221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40222. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  40223. __decorate([
  40224. BABYLON.serialize(),
  40225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40226. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  40227. __decorate([
  40228. BABYLON.serialize(),
  40229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40230. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  40231. __decorate([
  40232. BABYLON.serialize(),
  40233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40234. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  40235. __decorate([
  40236. BABYLON.serialize(),
  40237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40238. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  40239. __decorate([
  40240. BABYLON.serialize(),
  40241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40242. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  40243. __decorate([
  40244. BABYLON.serialize(),
  40245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40246. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  40247. __decorate([
  40248. BABYLON.serialize(),
  40249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40250. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  40251. __decorate([
  40252. BABYLON.serialize(),
  40253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40254. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  40255. __decorate([
  40256. BABYLON.serialize(),
  40257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40258. ], PBRMaterial.prototype, "useParallax", void 0);
  40259. __decorate([
  40260. BABYLON.serialize(),
  40261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40262. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  40263. __decorate([
  40264. BABYLON.serialize(),
  40265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40266. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  40267. __decorate([
  40268. BABYLON.serialize(),
  40269. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40270. ], PBRMaterial.prototype, "disableLighting", void 0);
  40271. __decorate([
  40272. BABYLON.serialize(),
  40273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40274. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  40275. __decorate([
  40276. BABYLON.serialize(),
  40277. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40278. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40279. __decorate([
  40280. BABYLON.serialize(),
  40281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40282. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40283. __decorate([
  40284. BABYLON.serialize(),
  40285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40286. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40287. __decorate([
  40288. BABYLON.serialize(),
  40289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40290. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40291. __decorate([
  40292. BABYLON.serialize(),
  40293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40294. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  40295. __decorate([
  40296. BABYLON.serialize(),
  40297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40298. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  40299. __decorate([
  40300. BABYLON.serializeAsTexture(),
  40301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40302. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  40303. __decorate([
  40304. BABYLON.serialize(),
  40305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40306. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  40307. __decorate([
  40308. BABYLON.serialize(),
  40309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40310. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  40311. __decorate([
  40312. BABYLON.serialize(),
  40313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40314. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  40315. return PBRMaterial;
  40316. }(BABYLON.PBRBaseMaterial));
  40317. BABYLON.PBRMaterial = PBRMaterial;
  40318. })(BABYLON || (BABYLON = {}));
  40319. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40320. var BABYLON;
  40321. (function (BABYLON) {
  40322. /**
  40323. * The PBR material of BJS following the metal roughness convention.
  40324. *
  40325. * This fits to the PBR convention in the GLTF definition:
  40326. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40327. */
  40328. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  40329. __extends(PBRMetallicRoughnessMaterial, _super);
  40330. /**
  40331. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40332. *
  40333. * @param name The material name
  40334. * @param scene The scene the material will be use in.
  40335. */
  40336. function PBRMetallicRoughnessMaterial(name, scene) {
  40337. var _this = _super.call(this, name, scene) || this;
  40338. _this._useRoughnessFromMetallicTextureAlpha = false;
  40339. _this._useRoughnessFromMetallicTextureGreen = true;
  40340. _this._useMetallnessFromMetallicTextureBlue = true;
  40341. _this._forceMetallicWorkflow = true;
  40342. return _this;
  40343. }
  40344. /**
  40345. * Return the currrent class name of the material.
  40346. */
  40347. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40348. return "PBRMetallicRoughnessMaterial";
  40349. };
  40350. /**
  40351. * Return the active textures of the material.
  40352. */
  40353. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  40354. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40355. if (this.baseTexture) {
  40356. activeTextures.push(this.baseTexture);
  40357. }
  40358. if (this.metallicRoughnessTexture) {
  40359. activeTextures.push(this.metallicRoughnessTexture);
  40360. }
  40361. return activeTextures;
  40362. };
  40363. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  40364. if (_super.prototype.hasTexture.call(this, texture)) {
  40365. return true;
  40366. }
  40367. if (this.baseTexture === texture) {
  40368. return true;
  40369. }
  40370. if (this.metallicRoughnessTexture === texture) {
  40371. return true;
  40372. }
  40373. return false;
  40374. };
  40375. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  40376. var _this = this;
  40377. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  40378. clone.id = name;
  40379. clone.name = name;
  40380. return clone;
  40381. };
  40382. /**
  40383. * Serialize the material to a parsable JSON object.
  40384. */
  40385. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40386. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40387. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40388. return serializationObject;
  40389. };
  40390. /**
  40391. * Parses a JSON object correponding to the serialize function.
  40392. */
  40393. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40394. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40395. };
  40396. __decorate([
  40397. BABYLON.serializeAsColor3(),
  40398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40399. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40400. __decorate([
  40401. BABYLON.serializeAsTexture(),
  40402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40403. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40404. __decorate([
  40405. BABYLON.serialize(),
  40406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40407. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40408. __decorate([
  40409. BABYLON.serialize(),
  40410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40411. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40412. __decorate([
  40413. BABYLON.serializeAsTexture(),
  40414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40415. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40416. return PBRMetallicRoughnessMaterial;
  40417. }(BABYLON.PBRBaseSimpleMaterial));
  40418. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40419. })(BABYLON || (BABYLON = {}));
  40420. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40421. var BABYLON;
  40422. (function (BABYLON) {
  40423. /**
  40424. * The PBR material of BJS following the specular glossiness convention.
  40425. *
  40426. * This fits to the PBR convention in the GLTF definition:
  40427. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40428. */
  40429. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  40430. __extends(PBRSpecularGlossinessMaterial, _super);
  40431. /**
  40432. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40433. *
  40434. * @param name The material name
  40435. * @param scene The scene the material will be use in.
  40436. */
  40437. function PBRSpecularGlossinessMaterial(name, scene) {
  40438. var _this = _super.call(this, name, scene) || this;
  40439. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40440. return _this;
  40441. }
  40442. /**
  40443. * Return the currrent class name of the material.
  40444. */
  40445. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40446. return "PBRSpecularGlossinessMaterial";
  40447. };
  40448. /**
  40449. * Return the active textures of the material.
  40450. */
  40451. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  40452. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40453. if (this.diffuseTexture) {
  40454. activeTextures.push(this.diffuseTexture);
  40455. }
  40456. if (this.specularGlossinessTexture) {
  40457. activeTextures.push(this.specularGlossinessTexture);
  40458. }
  40459. return activeTextures;
  40460. };
  40461. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  40462. if (_super.prototype.hasTexture.call(this, texture)) {
  40463. return true;
  40464. }
  40465. if (this.diffuseTexture === texture) {
  40466. return true;
  40467. }
  40468. if (this.specularGlossinessTexture === texture) {
  40469. return true;
  40470. }
  40471. return false;
  40472. };
  40473. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  40474. var _this = this;
  40475. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  40476. clone.id = name;
  40477. clone.name = name;
  40478. return clone;
  40479. };
  40480. /**
  40481. * Serialize the material to a parsable JSON object.
  40482. */
  40483. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40484. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40485. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40486. return serializationObject;
  40487. };
  40488. /**
  40489. * Parses a JSON object correponding to the serialize function.
  40490. */
  40491. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40492. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40493. };
  40494. __decorate([
  40495. BABYLON.serializeAsColor3("diffuse"),
  40496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40497. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40498. __decorate([
  40499. BABYLON.serializeAsTexture(),
  40500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40501. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40502. __decorate([
  40503. BABYLON.serializeAsColor3("specular"),
  40504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40505. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40506. __decorate([
  40507. BABYLON.serialize(),
  40508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40509. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40510. __decorate([
  40511. BABYLON.serializeAsTexture(),
  40512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40513. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40514. return PBRSpecularGlossinessMaterial;
  40515. }(BABYLON.PBRBaseSimpleMaterial));
  40516. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40517. })(BABYLON || (BABYLON = {}));
  40518. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40519. var BABYLON;
  40520. (function (BABYLON) {
  40521. BABYLON.CameraInputTypes = {};
  40522. var CameraInputsManager = /** @class */ (function () {
  40523. function CameraInputsManager(camera) {
  40524. this.attached = {};
  40525. this.camera = camera;
  40526. this.checkInputs = function () { };
  40527. }
  40528. /**
  40529. * Add an input method to a camera.
  40530. * builtin inputs example: camera.inputs.addGamepad();
  40531. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40532. * @param input camera input method
  40533. */
  40534. CameraInputsManager.prototype.add = function (input) {
  40535. var type = input.getSimpleName();
  40536. if (this.attached[type]) {
  40537. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40538. return;
  40539. }
  40540. this.attached[type] = input;
  40541. input.camera = this.camera;
  40542. //for checkInputs, we are dynamically creating a function
  40543. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40544. if (input.checkInputs) {
  40545. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40546. }
  40547. if (this.attachedElement) {
  40548. input.attachControl(this.attachedElement);
  40549. }
  40550. };
  40551. /**
  40552. * Remove a specific input method from a camera
  40553. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40554. * @param inputToRemove camera input method
  40555. */
  40556. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40557. for (var cam in this.attached) {
  40558. var input = this.attached[cam];
  40559. if (input === inputToRemove) {
  40560. input.detachControl(this.attachedElement);
  40561. input.camera = null;
  40562. delete this.attached[cam];
  40563. this.rebuildInputCheck();
  40564. }
  40565. }
  40566. };
  40567. CameraInputsManager.prototype.removeByType = function (inputType) {
  40568. for (var cam in this.attached) {
  40569. var input = this.attached[cam];
  40570. if (input.getClassName() === inputType) {
  40571. input.detachControl(this.attachedElement);
  40572. input.camera = null;
  40573. delete this.attached[cam];
  40574. this.rebuildInputCheck();
  40575. }
  40576. }
  40577. };
  40578. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40579. var current = this.checkInputs;
  40580. return function () {
  40581. current();
  40582. fn();
  40583. };
  40584. };
  40585. CameraInputsManager.prototype.attachInput = function (input) {
  40586. if (this.attachedElement) {
  40587. input.attachControl(this.attachedElement, this.noPreventDefault);
  40588. }
  40589. };
  40590. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40591. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40592. if (this.attachedElement) {
  40593. return;
  40594. }
  40595. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40596. this.attachedElement = element;
  40597. this.noPreventDefault = noPreventDefault;
  40598. for (var cam in this.attached) {
  40599. this.attached[cam].attachControl(element, noPreventDefault);
  40600. }
  40601. };
  40602. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40603. if (disconnect === void 0) { disconnect = false; }
  40604. if (this.attachedElement !== element) {
  40605. return;
  40606. }
  40607. for (var cam in this.attached) {
  40608. this.attached[cam].detachControl(element);
  40609. if (disconnect) {
  40610. this.attached[cam].camera = null;
  40611. }
  40612. }
  40613. this.attachedElement = null;
  40614. };
  40615. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40616. this.checkInputs = function () { };
  40617. for (var cam in this.attached) {
  40618. var input = this.attached[cam];
  40619. if (input.checkInputs) {
  40620. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40621. }
  40622. }
  40623. };
  40624. /**
  40625. * Remove all attached input methods from a camera
  40626. */
  40627. CameraInputsManager.prototype.clear = function () {
  40628. if (this.attachedElement) {
  40629. this.detachElement(this.attachedElement, true);
  40630. }
  40631. this.attached = {};
  40632. this.attachedElement = null;
  40633. this.checkInputs = function () { };
  40634. };
  40635. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40636. var inputs = {};
  40637. for (var cam in this.attached) {
  40638. var input = this.attached[cam];
  40639. var res = BABYLON.SerializationHelper.Serialize(input);
  40640. inputs[input.getClassName()] = res;
  40641. }
  40642. serializedCamera.inputsmgr = inputs;
  40643. };
  40644. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40645. var parsedInputs = parsedCamera.inputsmgr;
  40646. if (parsedInputs) {
  40647. this.clear();
  40648. for (var n in parsedInputs) {
  40649. var construct = BABYLON.CameraInputTypes[n];
  40650. if (construct) {
  40651. var parsedinput = parsedInputs[n];
  40652. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40653. this.add(input);
  40654. }
  40655. }
  40656. }
  40657. else {
  40658. //2016-03-08 this part is for managing backward compatibility
  40659. for (var n in this.attached) {
  40660. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40661. if (construct) {
  40662. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40663. this.remove(this.attached[n]);
  40664. this.add(input);
  40665. }
  40666. }
  40667. }
  40668. };
  40669. return CameraInputsManager;
  40670. }());
  40671. BABYLON.CameraInputsManager = CameraInputsManager;
  40672. })(BABYLON || (BABYLON = {}));
  40673. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40674. var BABYLON;
  40675. (function (BABYLON) {
  40676. var TargetCamera = /** @class */ (function (_super) {
  40677. __extends(TargetCamera, _super);
  40678. function TargetCamera(name, position, scene) {
  40679. var _this = _super.call(this, name, position, scene) || this;
  40680. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40681. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40682. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40683. _this.speed = 2.0;
  40684. _this.noRotationConstraint = false;
  40685. _this.lockedTarget = null;
  40686. _this._currentTarget = BABYLON.Vector3.Zero();
  40687. _this._viewMatrix = BABYLON.Matrix.Zero();
  40688. _this._camMatrix = BABYLON.Matrix.Zero();
  40689. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40690. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40691. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40692. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40693. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40694. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40695. _this._tempMatrix = BABYLON.Matrix.Zero();
  40696. return _this;
  40697. }
  40698. TargetCamera.prototype.getFrontPosition = function (distance) {
  40699. this.getWorldMatrix();
  40700. var direction = this.getTarget().subtract(this.position);
  40701. direction.normalize();
  40702. direction.scaleInPlace(distance);
  40703. return this.globalPosition.add(direction);
  40704. };
  40705. TargetCamera.prototype._getLockedTargetPosition = function () {
  40706. if (!this.lockedTarget) {
  40707. return null;
  40708. }
  40709. if (this.lockedTarget.absolutePosition) {
  40710. this.lockedTarget.computeWorldMatrix();
  40711. }
  40712. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40713. };
  40714. TargetCamera.prototype.storeState = function () {
  40715. this._storedPosition = this.position.clone();
  40716. this._storedRotation = this.rotation.clone();
  40717. if (this.rotationQuaternion) {
  40718. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40719. }
  40720. return _super.prototype.storeState.call(this);
  40721. };
  40722. /**
  40723. * Restored camera state. You must call storeState() first
  40724. */
  40725. TargetCamera.prototype._restoreStateValues = function () {
  40726. if (!_super.prototype._restoreStateValues.call(this)) {
  40727. return false;
  40728. }
  40729. this.position = this._storedPosition.clone();
  40730. this.rotation = this._storedRotation.clone();
  40731. if (this.rotationQuaternion) {
  40732. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40733. }
  40734. this.cameraDirection.copyFromFloats(0, 0, 0);
  40735. this.cameraRotation.copyFromFloats(0, 0);
  40736. return true;
  40737. };
  40738. // Cache
  40739. TargetCamera.prototype._initCache = function () {
  40740. _super.prototype._initCache.call(this);
  40741. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40742. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40743. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40744. };
  40745. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40746. if (!ignoreParentClass) {
  40747. _super.prototype._updateCache.call(this);
  40748. }
  40749. var lockedTargetPosition = this._getLockedTargetPosition();
  40750. if (!lockedTargetPosition) {
  40751. this._cache.lockedTarget = null;
  40752. }
  40753. else {
  40754. if (!this._cache.lockedTarget) {
  40755. this._cache.lockedTarget = lockedTargetPosition.clone();
  40756. }
  40757. else {
  40758. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40759. }
  40760. }
  40761. this._cache.rotation.copyFrom(this.rotation);
  40762. if (this.rotationQuaternion)
  40763. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40764. };
  40765. // Synchronized
  40766. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40767. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40768. return false;
  40769. }
  40770. var lockedTargetPosition = this._getLockedTargetPosition();
  40771. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40772. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40773. };
  40774. // Methods
  40775. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40776. var engine = this.getEngine();
  40777. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40778. };
  40779. // Target
  40780. TargetCamera.prototype.setTarget = function (target) {
  40781. this.upVector.normalize();
  40782. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40783. this._camMatrix.invert();
  40784. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40785. var vDir = target.subtract(this.position);
  40786. if (vDir.x >= 0.0) {
  40787. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40788. }
  40789. else {
  40790. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40791. }
  40792. this.rotation.z = 0;
  40793. if (isNaN(this.rotation.x)) {
  40794. this.rotation.x = 0;
  40795. }
  40796. if (isNaN(this.rotation.y)) {
  40797. this.rotation.y = 0;
  40798. }
  40799. if (isNaN(this.rotation.z)) {
  40800. this.rotation.z = 0;
  40801. }
  40802. if (this.rotationQuaternion) {
  40803. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40804. }
  40805. };
  40806. /**
  40807. * Return the current target position of the camera. This value is expressed in local space.
  40808. */
  40809. TargetCamera.prototype.getTarget = function () {
  40810. return this._currentTarget;
  40811. };
  40812. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40813. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40814. };
  40815. TargetCamera.prototype._updatePosition = function () {
  40816. if (this.parent) {
  40817. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40818. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40819. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40820. return;
  40821. }
  40822. this.position.addInPlace(this.cameraDirection);
  40823. };
  40824. TargetCamera.prototype._checkInputs = function () {
  40825. var needToMove = this._decideIfNeedsToMove();
  40826. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40827. // Move
  40828. if (needToMove) {
  40829. this._updatePosition();
  40830. }
  40831. // Rotate
  40832. if (needToRotate) {
  40833. this.rotation.x += this.cameraRotation.x;
  40834. this.rotation.y += this.cameraRotation.y;
  40835. //rotate, if quaternion is set and rotation was used
  40836. if (this.rotationQuaternion) {
  40837. var len = this.rotation.lengthSquared();
  40838. if (len) {
  40839. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40840. }
  40841. }
  40842. if (!this.noRotationConstraint) {
  40843. var limit = (Math.PI / 2) * 0.95;
  40844. if (this.rotation.x > limit)
  40845. this.rotation.x = limit;
  40846. if (this.rotation.x < -limit)
  40847. this.rotation.x = -limit;
  40848. }
  40849. }
  40850. // Inertia
  40851. if (needToMove) {
  40852. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40853. this.cameraDirection.x = 0;
  40854. }
  40855. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40856. this.cameraDirection.y = 0;
  40857. }
  40858. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40859. this.cameraDirection.z = 0;
  40860. }
  40861. this.cameraDirection.scaleInPlace(this.inertia);
  40862. }
  40863. if (needToRotate) {
  40864. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40865. this.cameraRotation.x = 0;
  40866. }
  40867. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40868. this.cameraRotation.y = 0;
  40869. }
  40870. this.cameraRotation.scaleInPlace(this.inertia);
  40871. }
  40872. _super.prototype._checkInputs.call(this);
  40873. };
  40874. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40875. if (this.rotationQuaternion) {
  40876. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40877. }
  40878. else {
  40879. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40880. }
  40881. //update the up vector!
  40882. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40883. };
  40884. TargetCamera.prototype._getViewMatrix = function () {
  40885. if (this.lockedTarget) {
  40886. this.setTarget(this._getLockedTargetPosition());
  40887. }
  40888. // Compute
  40889. this._updateCameraRotationMatrix();
  40890. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40891. // Computing target and final matrix
  40892. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40893. if (this.getScene().useRightHandedSystem) {
  40894. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40895. }
  40896. else {
  40897. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40898. }
  40899. return this._viewMatrix;
  40900. };
  40901. /**
  40902. * @override
  40903. * Override Camera.createRigCamera
  40904. */
  40905. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40906. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40907. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40908. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40909. if (!this.rotationQuaternion) {
  40910. this.rotationQuaternion = new BABYLON.Quaternion();
  40911. }
  40912. rigCamera._cameraRigParams = {};
  40913. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40914. }
  40915. return rigCamera;
  40916. }
  40917. return null;
  40918. };
  40919. /**
  40920. * @override
  40921. * Override Camera._updateRigCameras
  40922. */
  40923. TargetCamera.prototype._updateRigCameras = function () {
  40924. var camLeft = this._rigCameras[0];
  40925. var camRight = this._rigCameras[1];
  40926. switch (this.cameraRigMode) {
  40927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40928. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40929. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40930. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40931. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40932. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40933. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40934. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40935. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40936. camLeft.setTarget(this.getTarget());
  40937. camRight.setTarget(this.getTarget());
  40938. break;
  40939. case BABYLON.Camera.RIG_MODE_VR:
  40940. if (camLeft.rotationQuaternion) {
  40941. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40942. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40943. }
  40944. else {
  40945. camLeft.rotation.copyFrom(this.rotation);
  40946. camRight.rotation.copyFrom(this.rotation);
  40947. }
  40948. camLeft.position.copyFrom(this.position);
  40949. camRight.position.copyFrom(this.position);
  40950. break;
  40951. }
  40952. _super.prototype._updateRigCameras.call(this);
  40953. };
  40954. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40955. if (!this._rigCamTransformMatrix) {
  40956. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40957. }
  40958. var target = this.getTarget();
  40959. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40960. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40961. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40962. };
  40963. TargetCamera.prototype.getClassName = function () {
  40964. return "TargetCamera";
  40965. };
  40966. __decorate([
  40967. BABYLON.serializeAsVector3()
  40968. ], TargetCamera.prototype, "rotation", void 0);
  40969. __decorate([
  40970. BABYLON.serialize()
  40971. ], TargetCamera.prototype, "speed", void 0);
  40972. __decorate([
  40973. BABYLON.serializeAsMeshReference("lockedTargetId")
  40974. ], TargetCamera.prototype, "lockedTarget", void 0);
  40975. return TargetCamera;
  40976. }(BABYLON.Camera));
  40977. BABYLON.TargetCamera = TargetCamera;
  40978. })(BABYLON || (BABYLON = {}));
  40979. //# sourceMappingURL=babylon.targetCamera.js.map
  40980. var BABYLON;
  40981. (function (BABYLON) {
  40982. var FreeCameraMouseInput = /** @class */ (function () {
  40983. function FreeCameraMouseInput(touchEnabled) {
  40984. if (touchEnabled === void 0) { touchEnabled = true; }
  40985. this.touchEnabled = touchEnabled;
  40986. this.buttons = [0, 1, 2];
  40987. this.angularSensibility = 2000.0;
  40988. this.previousPosition = null;
  40989. }
  40990. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40991. var _this = this;
  40992. var engine = this.camera.getEngine();
  40993. if (!this._pointerInput) {
  40994. this._pointerInput = function (p, s) {
  40995. var evt = p.event;
  40996. if (engine.isInVRExclusivePointerMode) {
  40997. return;
  40998. }
  40999. if (!_this.touchEnabled && evt.pointerType === "touch") {
  41000. return;
  41001. }
  41002. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41003. return;
  41004. }
  41005. var srcElement = (evt.srcElement || evt.target);
  41006. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41007. try {
  41008. srcElement.setPointerCapture(evt.pointerId);
  41009. }
  41010. catch (e) {
  41011. //Nothing to do with the error. Execution will continue.
  41012. }
  41013. _this.previousPosition = {
  41014. x: evt.clientX,
  41015. y: evt.clientY
  41016. };
  41017. if (!noPreventDefault) {
  41018. evt.preventDefault();
  41019. element.focus();
  41020. }
  41021. }
  41022. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41023. try {
  41024. srcElement.releasePointerCapture(evt.pointerId);
  41025. }
  41026. catch (e) {
  41027. //Nothing to do with the error.
  41028. }
  41029. _this.previousPosition = null;
  41030. if (!noPreventDefault) {
  41031. evt.preventDefault();
  41032. }
  41033. }
  41034. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41035. if (!_this.previousPosition || engine.isPointerLock) {
  41036. return;
  41037. }
  41038. var offsetX = evt.clientX - _this.previousPosition.x;
  41039. var offsetY = evt.clientY - _this.previousPosition.y;
  41040. if (_this.camera.getScene().useRightHandedSystem) {
  41041. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41042. }
  41043. else {
  41044. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41045. }
  41046. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41047. _this.previousPosition = {
  41048. x: evt.clientX,
  41049. y: evt.clientY
  41050. };
  41051. if (!noPreventDefault) {
  41052. evt.preventDefault();
  41053. }
  41054. }
  41055. };
  41056. }
  41057. this._onMouseMove = function (evt) {
  41058. if (!engine.isPointerLock) {
  41059. return;
  41060. }
  41061. if (engine.isInVRExclusivePointerMode) {
  41062. return;
  41063. }
  41064. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41065. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41066. if (_this.camera.getScene().useRightHandedSystem) {
  41067. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  41068. }
  41069. else {
  41070. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  41071. }
  41072. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  41073. _this.previousPosition = null;
  41074. if (!noPreventDefault) {
  41075. evt.preventDefault();
  41076. }
  41077. };
  41078. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  41079. element.addEventListener("mousemove", this._onMouseMove, false);
  41080. };
  41081. FreeCameraMouseInput.prototype.detachControl = function (element) {
  41082. if (this._observer && element) {
  41083. this.camera.getScene().onPointerObservable.remove(this._observer);
  41084. if (this._onMouseMove) {
  41085. element.removeEventListener("mousemove", this._onMouseMove);
  41086. }
  41087. this._observer = null;
  41088. this._onMouseMove = null;
  41089. this.previousPosition = null;
  41090. }
  41091. };
  41092. FreeCameraMouseInput.prototype.getClassName = function () {
  41093. return "FreeCameraMouseInput";
  41094. };
  41095. FreeCameraMouseInput.prototype.getSimpleName = function () {
  41096. return "mouse";
  41097. };
  41098. __decorate([
  41099. BABYLON.serialize()
  41100. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  41101. __decorate([
  41102. BABYLON.serialize()
  41103. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  41104. return FreeCameraMouseInput;
  41105. }());
  41106. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  41107. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  41108. })(BABYLON || (BABYLON = {}));
  41109. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  41110. var BABYLON;
  41111. (function (BABYLON) {
  41112. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  41113. function FreeCameraKeyboardMoveInput() {
  41114. this._keys = new Array();
  41115. this.keysUp = [38];
  41116. this.keysDown = [40];
  41117. this.keysLeft = [37];
  41118. this.keysRight = [39];
  41119. }
  41120. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41121. var _this = this;
  41122. if (this._onCanvasBlurObserver) {
  41123. return;
  41124. }
  41125. this._scene = this.camera.getScene();
  41126. this._engine = this._scene.getEngine();
  41127. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41128. _this._keys = [];
  41129. });
  41130. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41131. var evt = info.event;
  41132. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41133. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41134. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41135. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41136. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41137. var index = _this._keys.indexOf(evt.keyCode);
  41138. if (index === -1) {
  41139. _this._keys.push(evt.keyCode);
  41140. }
  41141. if (!noPreventDefault) {
  41142. evt.preventDefault();
  41143. }
  41144. }
  41145. }
  41146. else {
  41147. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41148. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41149. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41150. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  41151. var index = _this._keys.indexOf(evt.keyCode);
  41152. if (index >= 0) {
  41153. _this._keys.splice(index, 1);
  41154. }
  41155. if (!noPreventDefault) {
  41156. evt.preventDefault();
  41157. }
  41158. }
  41159. }
  41160. });
  41161. };
  41162. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41163. if (this._scene) {
  41164. if (this._onKeyboardObserver) {
  41165. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41166. }
  41167. if (this._onCanvasBlurObserver) {
  41168. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41169. }
  41170. this._onKeyboardObserver = null;
  41171. this._onCanvasBlurObserver = null;
  41172. }
  41173. this._keys = [];
  41174. };
  41175. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41176. if (this._onKeyboardObserver) {
  41177. var camera = this.camera;
  41178. // Keyboard
  41179. for (var index = 0; index < this._keys.length; index++) {
  41180. var keyCode = this._keys[index];
  41181. var speed = camera._computeLocalCameraSpeed();
  41182. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41183. camera._localDirection.copyFromFloats(-speed, 0, 0);
  41184. }
  41185. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41186. camera._localDirection.copyFromFloats(0, 0, speed);
  41187. }
  41188. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41189. camera._localDirection.copyFromFloats(speed, 0, 0);
  41190. }
  41191. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41192. camera._localDirection.copyFromFloats(0, 0, -speed);
  41193. }
  41194. if (camera.getScene().useRightHandedSystem) {
  41195. camera._localDirection.z *= -1;
  41196. }
  41197. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  41198. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  41199. camera.cameraDirection.addInPlace(camera._transformedDirection);
  41200. }
  41201. }
  41202. };
  41203. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  41204. return "FreeCameraKeyboardMoveInput";
  41205. };
  41206. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  41207. this._keys = [];
  41208. };
  41209. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41210. return "keyboard";
  41211. };
  41212. __decorate([
  41213. BABYLON.serialize()
  41214. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41215. __decorate([
  41216. BABYLON.serialize()
  41217. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41218. __decorate([
  41219. BABYLON.serialize()
  41220. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41221. __decorate([
  41222. BABYLON.serialize()
  41223. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41224. return FreeCameraKeyboardMoveInput;
  41225. }());
  41226. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  41227. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  41228. })(BABYLON || (BABYLON = {}));
  41229. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  41230. var BABYLON;
  41231. (function (BABYLON) {
  41232. var FreeCameraInputsManager = /** @class */ (function (_super) {
  41233. __extends(FreeCameraInputsManager, _super);
  41234. function FreeCameraInputsManager(camera) {
  41235. return _super.call(this, camera) || this;
  41236. }
  41237. FreeCameraInputsManager.prototype.addKeyboard = function () {
  41238. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  41239. return this;
  41240. };
  41241. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  41242. if (touchEnabled === void 0) { touchEnabled = true; }
  41243. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  41244. return this;
  41245. };
  41246. FreeCameraInputsManager.prototype.addGamepad = function () {
  41247. this.add(new BABYLON.FreeCameraGamepadInput());
  41248. return this;
  41249. };
  41250. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  41251. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  41252. return this;
  41253. };
  41254. FreeCameraInputsManager.prototype.addTouch = function () {
  41255. this.add(new BABYLON.FreeCameraTouchInput());
  41256. return this;
  41257. };
  41258. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  41259. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  41260. return this;
  41261. };
  41262. return FreeCameraInputsManager;
  41263. }(BABYLON.CameraInputsManager));
  41264. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  41265. })(BABYLON || (BABYLON = {}));
  41266. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  41267. var BABYLON;
  41268. (function (BABYLON) {
  41269. var FreeCamera = /** @class */ (function (_super) {
  41270. __extends(FreeCamera, _super);
  41271. function FreeCamera(name, position, scene) {
  41272. var _this = _super.call(this, name, position, scene) || this;
  41273. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  41274. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  41275. _this.checkCollisions = false;
  41276. _this.applyGravity = false;
  41277. _this._needMoveForGravity = false;
  41278. _this._oldPosition = BABYLON.Vector3.Zero();
  41279. _this._diffPosition = BABYLON.Vector3.Zero();
  41280. _this._newPosition = BABYLON.Vector3.Zero();
  41281. // Collisions
  41282. _this._collisionMask = -1;
  41283. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41284. if (collidedMesh === void 0) { collidedMesh = null; }
  41285. //TODO move this to the collision coordinator!
  41286. if (_this.getScene().workerCollisions)
  41287. newPosition.multiplyInPlace(_this._collider._radius);
  41288. var updatePosition = function (newPos) {
  41289. _this._newPosition.copyFrom(newPos);
  41290. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  41291. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  41292. _this.position.addInPlace(_this._diffPosition);
  41293. if (_this.onCollide && collidedMesh) {
  41294. _this.onCollide(collidedMesh);
  41295. }
  41296. }
  41297. };
  41298. updatePosition(newPosition);
  41299. };
  41300. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  41301. _this.inputs.addKeyboard().addMouse();
  41302. return _this;
  41303. }
  41304. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  41305. //-- begin properties for backward compatibility for inputs
  41306. /**
  41307. * Gets the input sensibility for a mouse input. (default is 2000.0)
  41308. * Higher values reduce sensitivity.
  41309. */
  41310. get: function () {
  41311. var mouse = this.inputs.attached["mouse"];
  41312. if (mouse)
  41313. return mouse.angularSensibility;
  41314. return 0;
  41315. },
  41316. /**
  41317. * Sets the input sensibility for a mouse input. (default is 2000.0)
  41318. * Higher values reduce sensitivity.
  41319. */
  41320. set: function (value) {
  41321. var mouse = this.inputs.attached["mouse"];
  41322. if (mouse)
  41323. mouse.angularSensibility = value;
  41324. },
  41325. enumerable: true,
  41326. configurable: true
  41327. });
  41328. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  41329. get: function () {
  41330. var keyboard = this.inputs.attached["keyboard"];
  41331. if (keyboard)
  41332. return keyboard.keysUp;
  41333. return [];
  41334. },
  41335. set: function (value) {
  41336. var keyboard = this.inputs.attached["keyboard"];
  41337. if (keyboard)
  41338. keyboard.keysUp = value;
  41339. },
  41340. enumerable: true,
  41341. configurable: true
  41342. });
  41343. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  41344. get: function () {
  41345. var keyboard = this.inputs.attached["keyboard"];
  41346. if (keyboard)
  41347. return keyboard.keysDown;
  41348. return [];
  41349. },
  41350. set: function (value) {
  41351. var keyboard = this.inputs.attached["keyboard"];
  41352. if (keyboard)
  41353. keyboard.keysDown = value;
  41354. },
  41355. enumerable: true,
  41356. configurable: true
  41357. });
  41358. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  41359. get: function () {
  41360. var keyboard = this.inputs.attached["keyboard"];
  41361. if (keyboard)
  41362. return keyboard.keysLeft;
  41363. return [];
  41364. },
  41365. set: function (value) {
  41366. var keyboard = this.inputs.attached["keyboard"];
  41367. if (keyboard)
  41368. keyboard.keysLeft = value;
  41369. },
  41370. enumerable: true,
  41371. configurable: true
  41372. });
  41373. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  41374. get: function () {
  41375. var keyboard = this.inputs.attached["keyboard"];
  41376. if (keyboard)
  41377. return keyboard.keysRight;
  41378. return [];
  41379. },
  41380. set: function (value) {
  41381. var keyboard = this.inputs.attached["keyboard"];
  41382. if (keyboard)
  41383. keyboard.keysRight = value;
  41384. },
  41385. enumerable: true,
  41386. configurable: true
  41387. });
  41388. // Controls
  41389. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  41390. this.inputs.attachElement(element, noPreventDefault);
  41391. };
  41392. FreeCamera.prototype.detachControl = function (element) {
  41393. this.inputs.detachElement(element);
  41394. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41395. this.cameraRotation = new BABYLON.Vector2(0, 0);
  41396. };
  41397. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  41398. get: function () {
  41399. return this._collisionMask;
  41400. },
  41401. set: function (mask) {
  41402. this._collisionMask = !isNaN(mask) ? mask : -1;
  41403. },
  41404. enumerable: true,
  41405. configurable: true
  41406. });
  41407. FreeCamera.prototype._collideWithWorld = function (displacement) {
  41408. var globalPosition;
  41409. if (this.parent) {
  41410. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  41411. }
  41412. else {
  41413. globalPosition = this.position;
  41414. }
  41415. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  41416. this._oldPosition.addInPlace(this.ellipsoidOffset);
  41417. if (!this._collider) {
  41418. this._collider = new BABYLON.Collider();
  41419. }
  41420. this._collider._radius = this.ellipsoid;
  41421. this._collider.collisionMask = this._collisionMask;
  41422. //no need for clone, as long as gravity is not on.
  41423. var actualDisplacement = displacement;
  41424. //add gravity to the direction to prevent the dual-collision checking
  41425. if (this.applyGravity) {
  41426. //this prevents mending with cameraDirection, a global variable of the free camera class.
  41427. actualDisplacement = displacement.add(this.getScene().gravity);
  41428. }
  41429. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41430. };
  41431. FreeCamera.prototype._checkInputs = function () {
  41432. if (!this._localDirection) {
  41433. this._localDirection = BABYLON.Vector3.Zero();
  41434. this._transformedDirection = BABYLON.Vector3.Zero();
  41435. }
  41436. this.inputs.checkInputs();
  41437. _super.prototype._checkInputs.call(this);
  41438. };
  41439. FreeCamera.prototype._decideIfNeedsToMove = function () {
  41440. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  41441. };
  41442. FreeCamera.prototype._updatePosition = function () {
  41443. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  41444. this._collideWithWorld(this.cameraDirection);
  41445. }
  41446. else {
  41447. _super.prototype._updatePosition.call(this);
  41448. }
  41449. };
  41450. FreeCamera.prototype.dispose = function () {
  41451. this.inputs.clear();
  41452. _super.prototype.dispose.call(this);
  41453. };
  41454. FreeCamera.prototype.getClassName = function () {
  41455. return "FreeCamera";
  41456. };
  41457. __decorate([
  41458. BABYLON.serializeAsVector3()
  41459. ], FreeCamera.prototype, "ellipsoid", void 0);
  41460. __decorate([
  41461. BABYLON.serializeAsVector3()
  41462. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  41463. __decorate([
  41464. BABYLON.serialize()
  41465. ], FreeCamera.prototype, "checkCollisions", void 0);
  41466. __decorate([
  41467. BABYLON.serialize()
  41468. ], FreeCamera.prototype, "applyGravity", void 0);
  41469. return FreeCamera;
  41470. }(BABYLON.TargetCamera));
  41471. BABYLON.FreeCamera = FreeCamera;
  41472. })(BABYLON || (BABYLON = {}));
  41473. //# sourceMappingURL=babylon.freeCamera.js.map
  41474. var BABYLON;
  41475. (function (BABYLON) {
  41476. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  41477. function ArcRotateCameraKeyboardMoveInput() {
  41478. this._keys = new Array();
  41479. this.keysUp = [38];
  41480. this.keysDown = [40];
  41481. this.keysLeft = [37];
  41482. this.keysRight = [39];
  41483. this.keysReset = [220];
  41484. this.panningSensibility = 50.0;
  41485. this.zoomingSensibility = 25.0;
  41486. this.useAltToZoom = true;
  41487. }
  41488. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41489. var _this = this;
  41490. if (this._onCanvasBlurObserver) {
  41491. return;
  41492. }
  41493. this._scene = this.camera.getScene();
  41494. this._engine = this._scene.getEngine();
  41495. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41496. _this._keys = [];
  41497. });
  41498. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41499. var evt = info.event;
  41500. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41501. _this._ctrlPressed = evt.ctrlKey;
  41502. _this._altPressed = evt.altKey;
  41503. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41504. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41505. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41506. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41507. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41508. var index = _this._keys.indexOf(evt.keyCode);
  41509. if (index === -1) {
  41510. _this._keys.push(evt.keyCode);
  41511. }
  41512. if (evt.preventDefault) {
  41513. if (!noPreventDefault) {
  41514. evt.preventDefault();
  41515. }
  41516. }
  41517. }
  41518. }
  41519. else {
  41520. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41521. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41522. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41523. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41524. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41525. var index = _this._keys.indexOf(evt.keyCode);
  41526. if (index >= 0) {
  41527. _this._keys.splice(index, 1);
  41528. }
  41529. if (evt.preventDefault) {
  41530. if (!noPreventDefault) {
  41531. evt.preventDefault();
  41532. }
  41533. }
  41534. }
  41535. }
  41536. });
  41537. };
  41538. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41539. if (this._scene) {
  41540. if (this._onKeyboardObserver) {
  41541. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41542. }
  41543. if (this._onCanvasBlurObserver) {
  41544. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41545. }
  41546. this._onKeyboardObserver = null;
  41547. this._onCanvasBlurObserver = null;
  41548. }
  41549. this._keys = [];
  41550. };
  41551. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41552. if (this._onKeyboardObserver) {
  41553. var camera = this.camera;
  41554. for (var index = 0; index < this._keys.length; index++) {
  41555. var keyCode = this._keys[index];
  41556. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41557. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41558. camera.inertialPanningX -= 1 / this.panningSensibility;
  41559. }
  41560. else {
  41561. camera.inertialAlphaOffset -= 0.01;
  41562. }
  41563. }
  41564. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41565. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41566. camera.inertialPanningY += 1 / this.panningSensibility;
  41567. }
  41568. else if (this._altPressed && this.useAltToZoom) {
  41569. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41570. }
  41571. else {
  41572. camera.inertialBetaOffset -= 0.01;
  41573. }
  41574. }
  41575. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41576. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41577. camera.inertialPanningX += 1 / this.panningSensibility;
  41578. }
  41579. else {
  41580. camera.inertialAlphaOffset += 0.01;
  41581. }
  41582. }
  41583. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41584. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41585. camera.inertialPanningY -= 1 / this.panningSensibility;
  41586. }
  41587. else if (this._altPressed && this.useAltToZoom) {
  41588. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41589. }
  41590. else {
  41591. camera.inertialBetaOffset += 0.01;
  41592. }
  41593. }
  41594. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41595. camera.restoreState();
  41596. }
  41597. }
  41598. }
  41599. };
  41600. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41601. return "ArcRotateCameraKeyboardMoveInput";
  41602. };
  41603. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41604. return "keyboard";
  41605. };
  41606. __decorate([
  41607. BABYLON.serialize()
  41608. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41609. __decorate([
  41610. BABYLON.serialize()
  41611. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41612. __decorate([
  41613. BABYLON.serialize()
  41614. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41615. __decorate([
  41616. BABYLON.serialize()
  41617. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41618. __decorate([
  41619. BABYLON.serialize()
  41620. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41621. __decorate([
  41622. BABYLON.serialize()
  41623. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41624. __decorate([
  41625. BABYLON.serialize()
  41626. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41627. __decorate([
  41628. BABYLON.serialize()
  41629. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41630. return ArcRotateCameraKeyboardMoveInput;
  41631. }());
  41632. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41633. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41634. })(BABYLON || (BABYLON = {}));
  41635. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41636. var BABYLON;
  41637. (function (BABYLON) {
  41638. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41639. function ArcRotateCameraMouseWheelInput() {
  41640. this.wheelPrecision = 3.0;
  41641. /**
  41642. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41643. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41644. */
  41645. this.wheelDeltaPercentage = 0;
  41646. }
  41647. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41648. var _this = this;
  41649. this._wheel = function (p, s) {
  41650. //sanity check - this should be a PointerWheel event.
  41651. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41652. return;
  41653. var event = p.event;
  41654. var delta = 0;
  41655. if (event.wheelDelta) {
  41656. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41657. }
  41658. else if (event.detail) {
  41659. delta = -event.detail / _this.wheelPrecision;
  41660. }
  41661. if (delta)
  41662. _this.camera.inertialRadiusOffset += delta;
  41663. if (event.preventDefault) {
  41664. if (!noPreventDefault) {
  41665. event.preventDefault();
  41666. }
  41667. }
  41668. };
  41669. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41670. };
  41671. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41672. if (this._observer && element) {
  41673. this.camera.getScene().onPointerObservable.remove(this._observer);
  41674. this._observer = null;
  41675. this._wheel = null;
  41676. }
  41677. };
  41678. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41679. return "ArcRotateCameraMouseWheelInput";
  41680. };
  41681. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41682. return "mousewheel";
  41683. };
  41684. __decorate([
  41685. BABYLON.serialize()
  41686. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41687. __decorate([
  41688. BABYLON.serialize()
  41689. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41690. return ArcRotateCameraMouseWheelInput;
  41691. }());
  41692. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41693. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41694. })(BABYLON || (BABYLON = {}));
  41695. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41696. var BABYLON;
  41697. (function (BABYLON) {
  41698. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41699. function ArcRotateCameraPointersInput() {
  41700. this.buttons = [0, 1, 2];
  41701. this.angularSensibilityX = 1000.0;
  41702. this.angularSensibilityY = 1000.0;
  41703. this.pinchPrecision = 12.0;
  41704. /**
  41705. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41706. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41707. */
  41708. this.pinchDeltaPercentage = 0;
  41709. this.panningSensibility = 1000.0;
  41710. this.multiTouchPanning = true;
  41711. this.multiTouchPanAndZoom = true;
  41712. this._isPanClick = false;
  41713. this.pinchInwards = true;
  41714. }
  41715. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41716. var _this = this;
  41717. var engine = this.camera.getEngine();
  41718. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41719. var pointA = null;
  41720. var pointB = null;
  41721. var previousPinchSquaredDistance = 0;
  41722. var initialDistance = 0;
  41723. var twoFingerActivityCount = 0;
  41724. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41725. this._pointerInput = function (p, s) {
  41726. var evt = p.event;
  41727. var isTouch = p.event.pointerType === "touch";
  41728. if (engine.isInVRExclusivePointerMode) {
  41729. return;
  41730. }
  41731. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41732. return;
  41733. }
  41734. var srcElement = (evt.srcElement || evt.target);
  41735. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41736. try {
  41737. srcElement.setPointerCapture(evt.pointerId);
  41738. }
  41739. catch (e) {
  41740. //Nothing to do with the error. Execution will continue.
  41741. }
  41742. // Manage panning with pan button click
  41743. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41744. // manage pointers
  41745. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41746. if (pointA === null) {
  41747. pointA = cacheSoloPointer;
  41748. }
  41749. else if (pointB === null) {
  41750. pointB = cacheSoloPointer;
  41751. }
  41752. if (!noPreventDefault) {
  41753. evt.preventDefault();
  41754. element.focus();
  41755. }
  41756. }
  41757. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41758. _this.camera.restoreState();
  41759. }
  41760. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41761. try {
  41762. srcElement.releasePointerCapture(evt.pointerId);
  41763. }
  41764. catch (e) {
  41765. //Nothing to do with the error.
  41766. }
  41767. cacheSoloPointer = null;
  41768. previousPinchSquaredDistance = 0;
  41769. previousMultiTouchPanPosition.isPaning = false;
  41770. previousMultiTouchPanPosition.isPinching = false;
  41771. twoFingerActivityCount = 0;
  41772. initialDistance = 0;
  41773. if (!isTouch) {
  41774. pointB = null; // Mouse and pen are mono pointer
  41775. }
  41776. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41777. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41778. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41779. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41780. if (engine.badOS) {
  41781. pointA = pointB = null;
  41782. }
  41783. else {
  41784. //only remove the impacted pointer in case of multitouch allowing on most
  41785. //platforms switching from rotate to zoom and pan seamlessly.
  41786. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41787. pointA = pointB;
  41788. pointB = null;
  41789. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41790. }
  41791. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41792. pointB = null;
  41793. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41794. }
  41795. else {
  41796. pointA = pointB = null;
  41797. }
  41798. }
  41799. if (!noPreventDefault) {
  41800. evt.preventDefault();
  41801. }
  41802. }
  41803. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41804. if (!noPreventDefault) {
  41805. evt.preventDefault();
  41806. }
  41807. // One button down
  41808. if (pointA && pointB === null && cacheSoloPointer) {
  41809. if (_this.panningSensibility !== 0 &&
  41810. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41811. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41812. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41813. }
  41814. else {
  41815. var offsetX = evt.clientX - cacheSoloPointer.x;
  41816. var offsetY = evt.clientY - cacheSoloPointer.y;
  41817. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41818. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41819. }
  41820. cacheSoloPointer.x = evt.clientX;
  41821. cacheSoloPointer.y = evt.clientY;
  41822. }
  41823. else if (pointA && pointB) {
  41824. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41825. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41826. ed.x = evt.clientX;
  41827. ed.y = evt.clientY;
  41828. var direction = _this.pinchInwards ? 1 : -1;
  41829. var distX = pointA.x - pointB.x;
  41830. var distY = pointA.y - pointB.y;
  41831. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41832. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41833. if (previousPinchSquaredDistance === 0) {
  41834. initialDistance = pinchDistance;
  41835. previousPinchSquaredDistance = pinchSquaredDistance;
  41836. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41837. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41838. return;
  41839. }
  41840. if (_this.multiTouchPanAndZoom) {
  41841. if (_this.pinchDeltaPercentage) {
  41842. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41843. }
  41844. else {
  41845. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41846. (_this.pinchPrecision *
  41847. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41848. direction);
  41849. }
  41850. if (_this.panningSensibility !== 0) {
  41851. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41852. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41853. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41854. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41855. previousMultiTouchPanPosition.x = pointersCenterX;
  41856. previousMultiTouchPanPosition.y = pointersCenterY;
  41857. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41858. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41859. }
  41860. }
  41861. else {
  41862. twoFingerActivityCount++;
  41863. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41864. if (_this.pinchDeltaPercentage) {
  41865. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41866. }
  41867. else {
  41868. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41869. (_this.pinchPrecision *
  41870. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41871. direction);
  41872. }
  41873. previousMultiTouchPanPosition.isPaning = false;
  41874. previousMultiTouchPanPosition.isPinching = true;
  41875. }
  41876. else {
  41877. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41878. if (!previousMultiTouchPanPosition.isPaning) {
  41879. previousMultiTouchPanPosition.isPaning = true;
  41880. previousMultiTouchPanPosition.isPinching = false;
  41881. previousMultiTouchPanPosition.x = ed.x;
  41882. previousMultiTouchPanPosition.y = ed.y;
  41883. return;
  41884. }
  41885. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41886. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41887. }
  41888. }
  41889. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41890. previousMultiTouchPanPosition.x = ed.x;
  41891. previousMultiTouchPanPosition.y = ed.y;
  41892. }
  41893. }
  41894. previousPinchSquaredDistance = pinchSquaredDistance;
  41895. }
  41896. }
  41897. };
  41898. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41899. this._onContextMenu = function (evt) {
  41900. evt.preventDefault();
  41901. };
  41902. if (!this.camera._useCtrlForPanning) {
  41903. element.addEventListener("contextmenu", this._onContextMenu, false);
  41904. }
  41905. this._onLostFocus = function () {
  41906. //this._keys = [];
  41907. pointA = pointB = null;
  41908. previousPinchSquaredDistance = 0;
  41909. previousMultiTouchPanPosition.isPaning = false;
  41910. previousMultiTouchPanPosition.isPinching = false;
  41911. twoFingerActivityCount = 0;
  41912. cacheSoloPointer = null;
  41913. initialDistance = 0;
  41914. };
  41915. this._onMouseMove = function (evt) {
  41916. if (!engine.isPointerLock) {
  41917. return;
  41918. }
  41919. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41920. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41921. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41922. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41923. if (!noPreventDefault) {
  41924. evt.preventDefault();
  41925. }
  41926. };
  41927. this._onGestureStart = function (e) {
  41928. if (window.MSGesture === undefined) {
  41929. return;
  41930. }
  41931. if (!_this._MSGestureHandler) {
  41932. _this._MSGestureHandler = new MSGesture();
  41933. _this._MSGestureHandler.target = element;
  41934. }
  41935. _this._MSGestureHandler.addPointer(e.pointerId);
  41936. };
  41937. this._onGesture = function (e) {
  41938. _this.camera.radius *= e.scale;
  41939. if (e.preventDefault) {
  41940. if (!noPreventDefault) {
  41941. e.stopPropagation();
  41942. e.preventDefault();
  41943. }
  41944. }
  41945. };
  41946. element.addEventListener("mousemove", this._onMouseMove, false);
  41947. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41948. element.addEventListener("MSGestureChange", this._onGesture, false);
  41949. BABYLON.Tools.RegisterTopRootEvents([
  41950. { name: "blur", handler: this._onLostFocus }
  41951. ]);
  41952. };
  41953. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41954. if (this._onLostFocus) {
  41955. BABYLON.Tools.UnregisterTopRootEvents([
  41956. { name: "blur", handler: this._onLostFocus }
  41957. ]);
  41958. }
  41959. if (element && this._observer) {
  41960. this.camera.getScene().onPointerObservable.remove(this._observer);
  41961. this._observer = null;
  41962. if (this._onContextMenu) {
  41963. element.removeEventListener("contextmenu", this._onContextMenu);
  41964. }
  41965. if (this._onMouseMove) {
  41966. element.removeEventListener("mousemove", this._onMouseMove);
  41967. }
  41968. if (this._onGestureStart) {
  41969. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41970. }
  41971. if (this._onGesture) {
  41972. element.removeEventListener("MSGestureChange", this._onGesture);
  41973. }
  41974. this._isPanClick = false;
  41975. this.pinchInwards = true;
  41976. this._onMouseMove = null;
  41977. this._onGestureStart = null;
  41978. this._onGesture = null;
  41979. this._MSGestureHandler = null;
  41980. this._onLostFocus = null;
  41981. this._onContextMenu = null;
  41982. }
  41983. };
  41984. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41985. return "ArcRotateCameraPointersInput";
  41986. };
  41987. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41988. return "pointers";
  41989. };
  41990. __decorate([
  41991. BABYLON.serialize()
  41992. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41993. __decorate([
  41994. BABYLON.serialize()
  41995. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41996. __decorate([
  41997. BABYLON.serialize()
  41998. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41999. __decorate([
  42000. BABYLON.serialize()
  42001. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  42002. __decorate([
  42003. BABYLON.serialize()
  42004. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  42005. __decorate([
  42006. BABYLON.serialize()
  42007. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  42008. __decorate([
  42009. BABYLON.serialize()
  42010. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  42011. __decorate([
  42012. BABYLON.serialize()
  42013. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  42014. return ArcRotateCameraPointersInput;
  42015. }());
  42016. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  42017. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  42018. })(BABYLON || (BABYLON = {}));
  42019. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  42020. var BABYLON;
  42021. (function (BABYLON) {
  42022. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  42023. __extends(ArcRotateCameraInputsManager, _super);
  42024. function ArcRotateCameraInputsManager(camera) {
  42025. return _super.call(this, camera) || this;
  42026. }
  42027. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  42028. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  42029. return this;
  42030. };
  42031. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  42032. this.add(new BABYLON.ArcRotateCameraPointersInput());
  42033. return this;
  42034. };
  42035. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  42036. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  42037. return this;
  42038. };
  42039. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  42040. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  42041. return this;
  42042. };
  42043. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  42044. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  42045. return this;
  42046. };
  42047. return ArcRotateCameraInputsManager;
  42048. }(BABYLON.CameraInputsManager));
  42049. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  42050. })(BABYLON || (BABYLON = {}));
  42051. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  42052. var BABYLON;
  42053. (function (BABYLON) {
  42054. var ArcRotateCamera = /** @class */ (function (_super) {
  42055. __extends(ArcRotateCamera, _super);
  42056. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  42057. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  42058. _this.inertialAlphaOffset = 0;
  42059. _this.inertialBetaOffset = 0;
  42060. _this.inertialRadiusOffset = 0;
  42061. _this.lowerAlphaLimit = null;
  42062. _this.upperAlphaLimit = null;
  42063. _this.lowerBetaLimit = 0.01;
  42064. _this.upperBetaLimit = Math.PI;
  42065. _this.lowerRadiusLimit = null;
  42066. _this.upperRadiusLimit = null;
  42067. _this.inertialPanningX = 0;
  42068. _this.inertialPanningY = 0;
  42069. _this.pinchToPanMaxDistance = 20;
  42070. _this.panningDistanceLimit = null;
  42071. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  42072. _this.panningInertia = 0.9;
  42073. //-- end properties for backward compatibility for inputs
  42074. _this.zoomOnFactor = 1;
  42075. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  42076. _this.allowUpsideDown = true;
  42077. _this._viewMatrix = new BABYLON.Matrix();
  42078. // Panning
  42079. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  42080. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  42081. _this.checkCollisions = false;
  42082. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42083. _this._previousPosition = BABYLON.Vector3.Zero();
  42084. _this._collisionVelocity = BABYLON.Vector3.Zero();
  42085. _this._newPosition = BABYLON.Vector3.Zero();
  42086. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42087. if (collidedMesh === void 0) { collidedMesh = null; }
  42088. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  42089. newPosition.multiplyInPlace(_this._collider._radius);
  42090. }
  42091. if (!collidedMesh) {
  42092. _this._previousPosition.copyFrom(_this.position);
  42093. }
  42094. else {
  42095. _this.setPosition(newPosition);
  42096. if (_this.onCollide) {
  42097. _this.onCollide(collidedMesh);
  42098. }
  42099. }
  42100. // Recompute because of constraints
  42101. var cosa = Math.cos(_this.alpha);
  42102. var sina = Math.sin(_this.alpha);
  42103. var cosb = Math.cos(_this.beta);
  42104. var sinb = Math.sin(_this.beta);
  42105. if (sinb === 0) {
  42106. sinb = 0.0001;
  42107. }
  42108. var target = _this._getTargetPosition();
  42109. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  42110. _this.position.copyFrom(_this._newPosition);
  42111. var up = _this.upVector;
  42112. if (_this.allowUpsideDown && _this.beta < 0) {
  42113. up = up.clone();
  42114. up = up.negate();
  42115. }
  42116. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  42117. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  42118. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  42119. _this._collisionTriggered = false;
  42120. };
  42121. _this._target = BABYLON.Vector3.Zero();
  42122. if (target) {
  42123. _this.setTarget(target);
  42124. }
  42125. _this.alpha = alpha;
  42126. _this.beta = beta;
  42127. _this.radius = radius;
  42128. _this.getViewMatrix();
  42129. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  42130. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  42131. return _this;
  42132. }
  42133. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  42134. get: function () {
  42135. return this._target;
  42136. },
  42137. set: function (value) {
  42138. this.setTarget(value);
  42139. },
  42140. enumerable: true,
  42141. configurable: true
  42142. });
  42143. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  42144. //-- begin properties for backward compatibility for inputs
  42145. get: function () {
  42146. var pointers = this.inputs.attached["pointers"];
  42147. if (pointers)
  42148. return pointers.angularSensibilityX;
  42149. return 0;
  42150. },
  42151. set: function (value) {
  42152. var pointers = this.inputs.attached["pointers"];
  42153. if (pointers) {
  42154. pointers.angularSensibilityX = value;
  42155. }
  42156. },
  42157. enumerable: true,
  42158. configurable: true
  42159. });
  42160. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  42161. get: function () {
  42162. var pointers = this.inputs.attached["pointers"];
  42163. if (pointers)
  42164. return pointers.angularSensibilityY;
  42165. return 0;
  42166. },
  42167. set: function (value) {
  42168. var pointers = this.inputs.attached["pointers"];
  42169. if (pointers) {
  42170. pointers.angularSensibilityY = value;
  42171. }
  42172. },
  42173. enumerable: true,
  42174. configurable: true
  42175. });
  42176. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  42177. get: function () {
  42178. var pointers = this.inputs.attached["pointers"];
  42179. if (pointers)
  42180. return pointers.pinchPrecision;
  42181. return 0;
  42182. },
  42183. set: function (value) {
  42184. var pointers = this.inputs.attached["pointers"];
  42185. if (pointers) {
  42186. pointers.pinchPrecision = value;
  42187. }
  42188. },
  42189. enumerable: true,
  42190. configurable: true
  42191. });
  42192. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  42193. get: function () {
  42194. var pointers = this.inputs.attached["pointers"];
  42195. if (pointers)
  42196. return pointers.pinchDeltaPercentage;
  42197. return 0;
  42198. },
  42199. set: function (value) {
  42200. var pointers = this.inputs.attached["pointers"];
  42201. if (pointers) {
  42202. pointers.pinchDeltaPercentage = value;
  42203. }
  42204. },
  42205. enumerable: true,
  42206. configurable: true
  42207. });
  42208. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  42209. get: function () {
  42210. var pointers = this.inputs.attached["pointers"];
  42211. if (pointers)
  42212. return pointers.panningSensibility;
  42213. return 0;
  42214. },
  42215. set: function (value) {
  42216. var pointers = this.inputs.attached["pointers"];
  42217. if (pointers) {
  42218. pointers.panningSensibility = value;
  42219. }
  42220. },
  42221. enumerable: true,
  42222. configurable: true
  42223. });
  42224. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  42225. get: function () {
  42226. var keyboard = this.inputs.attached["keyboard"];
  42227. if (keyboard)
  42228. return keyboard.keysUp;
  42229. return [];
  42230. },
  42231. set: function (value) {
  42232. var keyboard = this.inputs.attached["keyboard"];
  42233. if (keyboard)
  42234. keyboard.keysUp = value;
  42235. },
  42236. enumerable: true,
  42237. configurable: true
  42238. });
  42239. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  42240. get: function () {
  42241. var keyboard = this.inputs.attached["keyboard"];
  42242. if (keyboard)
  42243. return keyboard.keysDown;
  42244. return [];
  42245. },
  42246. set: function (value) {
  42247. var keyboard = this.inputs.attached["keyboard"];
  42248. if (keyboard)
  42249. keyboard.keysDown = value;
  42250. },
  42251. enumerable: true,
  42252. configurable: true
  42253. });
  42254. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  42255. get: function () {
  42256. var keyboard = this.inputs.attached["keyboard"];
  42257. if (keyboard)
  42258. return keyboard.keysLeft;
  42259. return [];
  42260. },
  42261. set: function (value) {
  42262. var keyboard = this.inputs.attached["keyboard"];
  42263. if (keyboard)
  42264. keyboard.keysLeft = value;
  42265. },
  42266. enumerable: true,
  42267. configurable: true
  42268. });
  42269. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  42270. get: function () {
  42271. var keyboard = this.inputs.attached["keyboard"];
  42272. if (keyboard)
  42273. return keyboard.keysRight;
  42274. return [];
  42275. },
  42276. set: function (value) {
  42277. var keyboard = this.inputs.attached["keyboard"];
  42278. if (keyboard)
  42279. keyboard.keysRight = value;
  42280. },
  42281. enumerable: true,
  42282. configurable: true
  42283. });
  42284. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  42285. get: function () {
  42286. var mousewheel = this.inputs.attached["mousewheel"];
  42287. if (mousewheel)
  42288. return mousewheel.wheelPrecision;
  42289. return 0;
  42290. },
  42291. set: function (value) {
  42292. var mousewheel = this.inputs.attached["mousewheel"];
  42293. if (mousewheel)
  42294. mousewheel.wheelPrecision = value;
  42295. },
  42296. enumerable: true,
  42297. configurable: true
  42298. });
  42299. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  42300. get: function () {
  42301. var mousewheel = this.inputs.attached["mousewheel"];
  42302. if (mousewheel)
  42303. return mousewheel.wheelDeltaPercentage;
  42304. return 0;
  42305. },
  42306. set: function (value) {
  42307. var mousewheel = this.inputs.attached["mousewheel"];
  42308. if (mousewheel)
  42309. mousewheel.wheelDeltaPercentage = value;
  42310. },
  42311. enumerable: true,
  42312. configurable: true
  42313. });
  42314. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  42315. get: function () {
  42316. return this._bouncingBehavior;
  42317. },
  42318. enumerable: true,
  42319. configurable: true
  42320. });
  42321. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  42322. get: function () {
  42323. return this._bouncingBehavior != null;
  42324. },
  42325. set: function (value) {
  42326. if (value === this.useBouncingBehavior) {
  42327. return;
  42328. }
  42329. if (value) {
  42330. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  42331. this.addBehavior(this._bouncingBehavior);
  42332. }
  42333. else if (this._bouncingBehavior) {
  42334. this.removeBehavior(this._bouncingBehavior);
  42335. this._bouncingBehavior = null;
  42336. }
  42337. },
  42338. enumerable: true,
  42339. configurable: true
  42340. });
  42341. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  42342. get: function () {
  42343. return this._framingBehavior;
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  42349. get: function () {
  42350. return this._framingBehavior != null;
  42351. },
  42352. set: function (value) {
  42353. if (value === this.useFramingBehavior) {
  42354. return;
  42355. }
  42356. if (value) {
  42357. this._framingBehavior = new BABYLON.FramingBehavior();
  42358. this.addBehavior(this._framingBehavior);
  42359. }
  42360. else if (this._framingBehavior) {
  42361. this.removeBehavior(this._framingBehavior);
  42362. this._framingBehavior = null;
  42363. }
  42364. },
  42365. enumerable: true,
  42366. configurable: true
  42367. });
  42368. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  42369. get: function () {
  42370. return this._autoRotationBehavior;
  42371. },
  42372. enumerable: true,
  42373. configurable: true
  42374. });
  42375. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  42376. get: function () {
  42377. return this._autoRotationBehavior != null;
  42378. },
  42379. set: function (value) {
  42380. if (value === this.useAutoRotationBehavior) {
  42381. return;
  42382. }
  42383. if (value) {
  42384. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  42385. this.addBehavior(this._autoRotationBehavior);
  42386. }
  42387. else if (this._autoRotationBehavior) {
  42388. this.removeBehavior(this._autoRotationBehavior);
  42389. this._autoRotationBehavior = null;
  42390. }
  42391. },
  42392. enumerable: true,
  42393. configurable: true
  42394. });
  42395. // Cache
  42396. ArcRotateCamera.prototype._initCache = function () {
  42397. _super.prototype._initCache.call(this);
  42398. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42399. this._cache.alpha = undefined;
  42400. this._cache.beta = undefined;
  42401. this._cache.radius = undefined;
  42402. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  42403. };
  42404. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  42405. if (!ignoreParentClass) {
  42406. _super.prototype._updateCache.call(this);
  42407. }
  42408. this._cache._target.copyFrom(this._getTargetPosition());
  42409. this._cache.alpha = this.alpha;
  42410. this._cache.beta = this.beta;
  42411. this._cache.radius = this.radius;
  42412. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  42413. };
  42414. ArcRotateCamera.prototype._getTargetPosition = function () {
  42415. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  42416. var pos = this._targetHost.getAbsolutePosition();
  42417. if (this._targetBoundingCenter) {
  42418. pos.addToRef(this._targetBoundingCenter, this._target);
  42419. }
  42420. else {
  42421. this._target.copyFrom(pos);
  42422. }
  42423. }
  42424. var lockedTargetPosition = this._getLockedTargetPosition();
  42425. if (lockedTargetPosition) {
  42426. return lockedTargetPosition;
  42427. }
  42428. return this._target;
  42429. };
  42430. ArcRotateCamera.prototype.storeState = function () {
  42431. this._storedAlpha = this.alpha;
  42432. this._storedBeta = this.beta;
  42433. this._storedRadius = this.radius;
  42434. this._storedTarget = this._getTargetPosition().clone();
  42435. return _super.prototype.storeState.call(this);
  42436. };
  42437. /**
  42438. * Restored camera state. You must call storeState() first
  42439. */
  42440. ArcRotateCamera.prototype._restoreStateValues = function () {
  42441. if (!_super.prototype._restoreStateValues.call(this)) {
  42442. return false;
  42443. }
  42444. this.alpha = this._storedAlpha;
  42445. this.beta = this._storedBeta;
  42446. this.radius = this._storedRadius;
  42447. this.setTarget(this._storedTarget.clone());
  42448. this.inertialAlphaOffset = 0;
  42449. this.inertialBetaOffset = 0;
  42450. this.inertialRadiusOffset = 0;
  42451. this.inertialPanningX = 0;
  42452. this.inertialPanningY = 0;
  42453. return true;
  42454. };
  42455. // Synchronized
  42456. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  42457. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  42458. return false;
  42459. return this._cache._target.equals(this._getTargetPosition())
  42460. && this._cache.alpha === this.alpha
  42461. && this._cache.beta === this.beta
  42462. && this._cache.radius === this.radius
  42463. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  42464. };
  42465. // Methods
  42466. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  42467. var _this = this;
  42468. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  42469. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  42470. this._useCtrlForPanning = useCtrlForPanning;
  42471. this._panningMouseButton = panningMouseButton;
  42472. this.inputs.attachElement(element, noPreventDefault);
  42473. this._reset = function () {
  42474. _this.inertialAlphaOffset = 0;
  42475. _this.inertialBetaOffset = 0;
  42476. _this.inertialRadiusOffset = 0;
  42477. _this.inertialPanningX = 0;
  42478. _this.inertialPanningY = 0;
  42479. };
  42480. };
  42481. ArcRotateCamera.prototype.detachControl = function (element) {
  42482. this.inputs.detachElement(element);
  42483. if (this._reset) {
  42484. this._reset();
  42485. }
  42486. };
  42487. ArcRotateCamera.prototype._checkInputs = function () {
  42488. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  42489. if (this._collisionTriggered) {
  42490. return;
  42491. }
  42492. this.inputs.checkInputs();
  42493. // Inertia
  42494. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  42495. if (this.getScene().useRightHandedSystem) {
  42496. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42497. }
  42498. else {
  42499. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42500. }
  42501. this.beta += this.inertialBetaOffset;
  42502. this.radius -= this.inertialRadiusOffset;
  42503. this.inertialAlphaOffset *= this.inertia;
  42504. this.inertialBetaOffset *= this.inertia;
  42505. this.inertialRadiusOffset *= this.inertia;
  42506. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  42507. this.inertialAlphaOffset = 0;
  42508. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  42509. this.inertialBetaOffset = 0;
  42510. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  42511. this.inertialRadiusOffset = 0;
  42512. }
  42513. // Panning inertia
  42514. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  42515. if (!this._localDirection) {
  42516. this._localDirection = BABYLON.Vector3.Zero();
  42517. this._transformedDirection = BABYLON.Vector3.Zero();
  42518. }
  42519. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42520. this._localDirection.multiplyInPlace(this.panningAxis);
  42521. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42522. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42523. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42524. if (!this.panningAxis.y) {
  42525. this._transformedDirection.y = 0;
  42526. }
  42527. if (!this._targetHost) {
  42528. if (this.panningDistanceLimit) {
  42529. this._transformedDirection.addInPlace(this._target);
  42530. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42531. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42532. this._target.copyFrom(this._transformedDirection);
  42533. }
  42534. }
  42535. else {
  42536. this._target.addInPlace(this._transformedDirection);
  42537. }
  42538. }
  42539. this.inertialPanningX *= this.panningInertia;
  42540. this.inertialPanningY *= this.panningInertia;
  42541. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42542. this.inertialPanningX = 0;
  42543. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42544. this.inertialPanningY = 0;
  42545. }
  42546. // Limits
  42547. this._checkLimits();
  42548. _super.prototype._checkInputs.call(this);
  42549. };
  42550. ArcRotateCamera.prototype._checkLimits = function () {
  42551. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42552. if (this.allowUpsideDown && this.beta > Math.PI) {
  42553. this.beta = this.beta - (2 * Math.PI);
  42554. }
  42555. }
  42556. else {
  42557. if (this.beta < this.lowerBetaLimit) {
  42558. this.beta = this.lowerBetaLimit;
  42559. }
  42560. }
  42561. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42562. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42563. this.beta = this.beta + (2 * Math.PI);
  42564. }
  42565. }
  42566. else {
  42567. if (this.beta > this.upperBetaLimit) {
  42568. this.beta = this.upperBetaLimit;
  42569. }
  42570. }
  42571. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42572. this.alpha = this.lowerAlphaLimit;
  42573. }
  42574. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42575. this.alpha = this.upperAlphaLimit;
  42576. }
  42577. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42578. this.radius = this.lowerRadiusLimit;
  42579. }
  42580. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42581. this.radius = this.upperRadiusLimit;
  42582. }
  42583. };
  42584. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42585. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42586. this.radius = radiusv3.length();
  42587. if (this.radius === 0) {
  42588. this.radius = 0.0001; // Just to avoid division by zero
  42589. }
  42590. // Alpha
  42591. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42592. if (radiusv3.z < 0) {
  42593. this.alpha = 2 * Math.PI - this.alpha;
  42594. }
  42595. // Beta
  42596. this.beta = Math.acos(radiusv3.y / this.radius);
  42597. this._checkLimits();
  42598. };
  42599. ArcRotateCamera.prototype.setPosition = function (position) {
  42600. if (this.position.equals(position)) {
  42601. return;
  42602. }
  42603. this.position.copyFrom(position);
  42604. this.rebuildAnglesAndRadius();
  42605. };
  42606. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42607. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42608. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42609. if (target.getBoundingInfo) {
  42610. if (toBoundingCenter) {
  42611. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42612. }
  42613. else {
  42614. this._targetBoundingCenter = null;
  42615. }
  42616. this._targetHost = target;
  42617. this._target = this._getTargetPosition();
  42618. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42619. }
  42620. else {
  42621. var newTarget = target;
  42622. var currentTarget = this._getTargetPosition();
  42623. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42624. return;
  42625. }
  42626. this._targetHost = null;
  42627. this._target = newTarget;
  42628. this._targetBoundingCenter = null;
  42629. this.onMeshTargetChangedObservable.notifyObservers(null);
  42630. }
  42631. this.rebuildAnglesAndRadius();
  42632. };
  42633. ArcRotateCamera.prototype._getViewMatrix = function () {
  42634. // Compute
  42635. var cosa = Math.cos(this.alpha);
  42636. var sina = Math.sin(this.alpha);
  42637. var cosb = Math.cos(this.beta);
  42638. var sinb = Math.sin(this.beta);
  42639. if (sinb === 0) {
  42640. sinb = 0.0001;
  42641. }
  42642. var target = this._getTargetPosition();
  42643. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42644. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42645. if (!this._collider) {
  42646. this._collider = new BABYLON.Collider();
  42647. }
  42648. this._collider._radius = this.collisionRadius;
  42649. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42650. this._collisionTriggered = true;
  42651. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42652. }
  42653. else {
  42654. this.position.copyFrom(this._newPosition);
  42655. var up = this.upVector;
  42656. if (this.allowUpsideDown && sinb < 0) {
  42657. up = up.clone();
  42658. up = up.negate();
  42659. }
  42660. if (this.getScene().useRightHandedSystem) {
  42661. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42662. }
  42663. else {
  42664. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42665. }
  42666. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42667. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42668. }
  42669. this._currentTarget = target;
  42670. return this._viewMatrix;
  42671. };
  42672. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42673. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42674. meshes = meshes || this.getScene().meshes;
  42675. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42676. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42677. this.radius = distance * this.zoomOnFactor;
  42678. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42679. };
  42680. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42681. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42682. var meshesOrMinMaxVector;
  42683. var distance;
  42684. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42685. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42686. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42687. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42688. }
  42689. else {
  42690. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42691. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42692. distance = minMaxVectorAndDistance.distance;
  42693. }
  42694. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42695. if (!doNotUpdateMaxZ) {
  42696. this.maxZ = distance * 2;
  42697. }
  42698. };
  42699. /**
  42700. * @override
  42701. * Override Camera.createRigCamera
  42702. */
  42703. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42704. var alphaShift = 0;
  42705. switch (this.cameraRigMode) {
  42706. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42707. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42708. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42709. case BABYLON.Camera.RIG_MODE_VR:
  42710. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42711. break;
  42712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42713. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42714. break;
  42715. }
  42716. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42717. rigCam._cameraRigParams = {};
  42718. return rigCam;
  42719. };
  42720. /**
  42721. * @override
  42722. * Override Camera._updateRigCameras
  42723. */
  42724. ArcRotateCamera.prototype._updateRigCameras = function () {
  42725. var camLeft = this._rigCameras[0];
  42726. var camRight = this._rigCameras[1];
  42727. camLeft.beta = camRight.beta = this.beta;
  42728. camLeft.radius = camRight.radius = this.radius;
  42729. switch (this.cameraRigMode) {
  42730. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42731. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42732. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42733. case BABYLON.Camera.RIG_MODE_VR:
  42734. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42735. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42736. break;
  42737. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42738. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42739. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42740. break;
  42741. }
  42742. _super.prototype._updateRigCameras.call(this);
  42743. };
  42744. ArcRotateCamera.prototype.dispose = function () {
  42745. this.inputs.clear();
  42746. _super.prototype.dispose.call(this);
  42747. };
  42748. ArcRotateCamera.prototype.getClassName = function () {
  42749. return "ArcRotateCamera";
  42750. };
  42751. __decorate([
  42752. BABYLON.serialize()
  42753. ], ArcRotateCamera.prototype, "alpha", void 0);
  42754. __decorate([
  42755. BABYLON.serialize()
  42756. ], ArcRotateCamera.prototype, "beta", void 0);
  42757. __decorate([
  42758. BABYLON.serialize()
  42759. ], ArcRotateCamera.prototype, "radius", void 0);
  42760. __decorate([
  42761. BABYLON.serializeAsVector3("target")
  42762. ], ArcRotateCamera.prototype, "_target", void 0);
  42763. __decorate([
  42764. BABYLON.serialize()
  42765. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42766. __decorate([
  42767. BABYLON.serialize()
  42768. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42769. __decorate([
  42770. BABYLON.serialize()
  42771. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42772. __decorate([
  42773. BABYLON.serialize()
  42774. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42775. __decorate([
  42776. BABYLON.serialize()
  42777. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42778. __decorate([
  42779. BABYLON.serialize()
  42780. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42781. __decorate([
  42782. BABYLON.serialize()
  42783. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42784. __decorate([
  42785. BABYLON.serialize()
  42786. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42787. __decorate([
  42788. BABYLON.serialize()
  42789. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42790. __decorate([
  42791. BABYLON.serialize()
  42792. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42793. __decorate([
  42794. BABYLON.serialize()
  42795. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42796. __decorate([
  42797. BABYLON.serialize()
  42798. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42799. __decorate([
  42800. BABYLON.serialize()
  42801. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42802. __decorate([
  42803. BABYLON.serializeAsVector3()
  42804. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42805. __decorate([
  42806. BABYLON.serialize()
  42807. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42808. __decorate([
  42809. BABYLON.serialize()
  42810. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42811. __decorate([
  42812. BABYLON.serialize()
  42813. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42814. return ArcRotateCamera;
  42815. }(BABYLON.TargetCamera));
  42816. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42817. })(BABYLON || (BABYLON = {}));
  42818. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42819. var BABYLON;
  42820. (function (BABYLON) {
  42821. /**
  42822. * The HemisphericLight simulates the ambient environment light,
  42823. * so the passed direction is the light reflection direction, not the incoming direction.
  42824. */
  42825. var HemisphericLight = /** @class */ (function (_super) {
  42826. __extends(HemisphericLight, _super);
  42827. /**
  42828. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42829. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42830. * The HemisphericLight can't cast shadows.
  42831. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42832. * @param name The friendly name of the light
  42833. * @param direction The direction of the light reflection
  42834. * @param scene The scene the light belongs to
  42835. */
  42836. function HemisphericLight(name, direction, scene) {
  42837. var _this = _super.call(this, name, scene) || this;
  42838. /**
  42839. * The groundColor is the light in the opposite direction to the one specified during creation.
  42840. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  42841. */
  42842. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42843. _this.direction = direction || BABYLON.Vector3.Up();
  42844. return _this;
  42845. }
  42846. HemisphericLight.prototype._buildUniformLayout = function () {
  42847. this._uniformBuffer.addUniform("vLightData", 4);
  42848. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42849. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42850. this._uniformBuffer.addUniform("vLightGround", 3);
  42851. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42852. this._uniformBuffer.addUniform("depthValues", 2);
  42853. this._uniformBuffer.create();
  42854. };
  42855. /**
  42856. * Returns the string "HemisphericLight".
  42857. * @return The class name
  42858. */
  42859. HemisphericLight.prototype.getClassName = function () {
  42860. return "HemisphericLight";
  42861. };
  42862. /**
  42863. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42864. * Returns the updated direction.
  42865. * @param target The target the direction should point to
  42866. * @return The computed direction
  42867. */
  42868. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42869. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42870. return this.direction;
  42871. };
  42872. /**
  42873. * Returns the shadow generator associated to the light.
  42874. * @returns Always null for hemispheric lights because it does not support shadows.
  42875. */
  42876. HemisphericLight.prototype.getShadowGenerator = function () {
  42877. return null;
  42878. };
  42879. /**
  42880. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42881. * @param effect The effect to update
  42882. * @param lightIndex The index of the light in the effect to update
  42883. * @returns The hemispheric light
  42884. */
  42885. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42886. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42887. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42888. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42889. return this;
  42890. };
  42891. /**
  42892. * @ignore internal use only.
  42893. */
  42894. HemisphericLight.prototype._getWorldMatrix = function () {
  42895. if (!this._worldMatrix) {
  42896. this._worldMatrix = BABYLON.Matrix.Identity();
  42897. }
  42898. return this._worldMatrix;
  42899. };
  42900. /**
  42901. * Returns the integer 3.
  42902. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  42903. */
  42904. HemisphericLight.prototype.getTypeID = function () {
  42905. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42906. };
  42907. __decorate([
  42908. BABYLON.serializeAsColor3()
  42909. ], HemisphericLight.prototype, "groundColor", void 0);
  42910. __decorate([
  42911. BABYLON.serializeAsVector3()
  42912. ], HemisphericLight.prototype, "direction", void 0);
  42913. return HemisphericLight;
  42914. }(BABYLON.Light));
  42915. BABYLON.HemisphericLight = HemisphericLight;
  42916. })(BABYLON || (BABYLON = {}));
  42917. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42918. var BABYLON;
  42919. (function (BABYLON) {
  42920. /**
  42921. * Base implementation of @see IShadowLight
  42922. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  42923. */
  42924. var ShadowLight = /** @class */ (function (_super) {
  42925. __extends(ShadowLight, _super);
  42926. function ShadowLight() {
  42927. var _this = _super !== null && _super.apply(this, arguments) || this;
  42928. _this._needProjectionMatrixCompute = true;
  42929. return _this;
  42930. }
  42931. Object.defineProperty(ShadowLight.prototype, "direction", {
  42932. get: function () {
  42933. return this._direction;
  42934. },
  42935. /**
  42936. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  42937. */
  42938. set: function (value) {
  42939. this._direction = value;
  42940. },
  42941. enumerable: true,
  42942. configurable: true
  42943. });
  42944. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42945. /**
  42946. * Gets the shadow projection clipping minimum z value.
  42947. */
  42948. get: function () {
  42949. return this._shadowMinZ;
  42950. },
  42951. /**
  42952. * Sets the shadow projection clipping minimum z value.
  42953. */
  42954. set: function (value) {
  42955. this._shadowMinZ = value;
  42956. this.forceProjectionMatrixCompute();
  42957. },
  42958. enumerable: true,
  42959. configurable: true
  42960. });
  42961. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42962. /**
  42963. * Sets the shadow projection clipping maximum z value.
  42964. */
  42965. get: function () {
  42966. return this._shadowMaxZ;
  42967. },
  42968. /**
  42969. * Gets the shadow projection clipping maximum z value.
  42970. */
  42971. set: function (value) {
  42972. this._shadowMaxZ = value;
  42973. this.forceProjectionMatrixCompute();
  42974. },
  42975. enumerable: true,
  42976. configurable: true
  42977. });
  42978. /**
  42979. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  42980. * @returns true if the information has been computed, false if it does not need to (no parenting)
  42981. */
  42982. ShadowLight.prototype.computeTransformedInformation = function () {
  42983. if (this.parent && this.parent.getWorldMatrix) {
  42984. if (!this.transformedPosition) {
  42985. this.transformedPosition = BABYLON.Vector3.Zero();
  42986. }
  42987. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42988. // In case the direction is present.
  42989. if (this.direction) {
  42990. if (!this.transformedDirection) {
  42991. this.transformedDirection = BABYLON.Vector3.Zero();
  42992. }
  42993. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42994. }
  42995. return true;
  42996. }
  42997. return false;
  42998. };
  42999. /**
  43000. * Return the depth scale used for the shadow map.
  43001. * @returns the depth scale.
  43002. */
  43003. ShadowLight.prototype.getDepthScale = function () {
  43004. return 50.0;
  43005. };
  43006. /**
  43007. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  43008. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43009. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43010. */
  43011. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  43012. return this.transformedDirection ? this.transformedDirection : this.direction;
  43013. };
  43014. /**
  43015. * Returns the ShadowLight absolute position in the World.
  43016. * @returns the position vector in world space
  43017. */
  43018. ShadowLight.prototype.getAbsolutePosition = function () {
  43019. return this.transformedPosition ? this.transformedPosition : this.position;
  43020. };
  43021. /**
  43022. * Sets the ShadowLight direction toward the passed target.
  43023. * @param target The point tot target in local space
  43024. * @returns the updated ShadowLight direction
  43025. */
  43026. ShadowLight.prototype.setDirectionToTarget = function (target) {
  43027. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  43028. return this.direction;
  43029. };
  43030. /**
  43031. * Returns the light rotation in euler definition.
  43032. * @returns the x y z rotation in local space.
  43033. */
  43034. ShadowLight.prototype.getRotation = function () {
  43035. this.direction.normalize();
  43036. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  43037. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  43038. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  43039. };
  43040. /**
  43041. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  43042. * @returns true if a cube texture needs to be use
  43043. */
  43044. ShadowLight.prototype.needCube = function () {
  43045. return false;
  43046. };
  43047. /**
  43048. * Detects if the projection matrix requires to be recomputed this frame.
  43049. * @returns true if it requires to be recomputed otherwise, false.
  43050. */
  43051. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  43052. return this._needProjectionMatrixCompute;
  43053. };
  43054. /**
  43055. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  43056. */
  43057. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  43058. this._needProjectionMatrixCompute = true;
  43059. };
  43060. /**
  43061. * Get the world matrix of the sahdow lights.
  43062. * @ignore Internal Use Only
  43063. */
  43064. ShadowLight.prototype._getWorldMatrix = function () {
  43065. if (!this._worldMatrix) {
  43066. this._worldMatrix = BABYLON.Matrix.Identity();
  43067. }
  43068. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  43069. return this._worldMatrix;
  43070. };
  43071. /**
  43072. * Gets the minZ used for shadow according to both the scene and the light.
  43073. * @param activeCamera The camera we are returning the min for
  43074. * @returns the depth min z
  43075. */
  43076. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  43077. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  43078. };
  43079. /**
  43080. * Gets the maxZ used for shadow according to both the scene and the light.
  43081. * @param activeCamera The camera we are returning the max for
  43082. * @returns the depth max z
  43083. */
  43084. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  43085. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  43086. };
  43087. /**
  43088. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  43089. * @param matrix The materix to updated with the projection information
  43090. * @param viewMatrix The transform matrix of the light
  43091. * @param renderList The list of mesh to render in the map
  43092. * @returns The current light
  43093. */
  43094. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43095. if (this.customProjectionMatrixBuilder) {
  43096. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  43097. }
  43098. else {
  43099. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43100. }
  43101. return this;
  43102. };
  43103. __decorate([
  43104. BABYLON.serializeAsVector3()
  43105. ], ShadowLight.prototype, "position", void 0);
  43106. __decorate([
  43107. BABYLON.serializeAsVector3()
  43108. /**
  43109. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  43110. */
  43111. ], ShadowLight.prototype, "direction", null);
  43112. __decorate([
  43113. BABYLON.serialize()
  43114. ], ShadowLight.prototype, "shadowMinZ", null);
  43115. __decorate([
  43116. BABYLON.serialize()
  43117. ], ShadowLight.prototype, "shadowMaxZ", null);
  43118. return ShadowLight;
  43119. }(BABYLON.Light));
  43120. BABYLON.ShadowLight = ShadowLight;
  43121. })(BABYLON || (BABYLON = {}));
  43122. //# sourceMappingURL=babylon.shadowLight.js.map
  43123. var BABYLON;
  43124. (function (BABYLON) {
  43125. /**
  43126. * A point light is a light defined by an unique point in world space.
  43127. * The light is emitted in every direction from this point.
  43128. * A good example of a point light is a standard light bulb.
  43129. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43130. */
  43131. var PointLight = /** @class */ (function (_super) {
  43132. __extends(PointLight, _super);
  43133. /**
  43134. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  43135. * A PointLight emits the light in every direction.
  43136. * It can cast shadows.
  43137. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  43138. * ```javascript
  43139. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  43140. * ```
  43141. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43142. * @param name The light friendly name
  43143. * @param position The position of the point light in the scene
  43144. * @param scene The scene the lights belongs to
  43145. */
  43146. function PointLight(name, position, scene) {
  43147. var _this = _super.call(this, name, scene) || this;
  43148. _this._shadowAngle = Math.PI / 2;
  43149. _this.position = position;
  43150. return _this;
  43151. }
  43152. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  43153. /**
  43154. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43155. * This specifies what angle the shadow will use to be created.
  43156. *
  43157. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43158. */
  43159. get: function () {
  43160. return this._shadowAngle;
  43161. },
  43162. /**
  43163. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43164. * This specifies what angle the shadow will use to be created.
  43165. *
  43166. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  43167. */
  43168. set: function (value) {
  43169. this._shadowAngle = value;
  43170. this.forceProjectionMatrixCompute();
  43171. },
  43172. enumerable: true,
  43173. configurable: true
  43174. });
  43175. Object.defineProperty(PointLight.prototype, "direction", {
  43176. /**
  43177. * Gets the direction if it has been set.
  43178. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43179. */
  43180. get: function () {
  43181. return this._direction;
  43182. },
  43183. /**
  43184. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  43185. */
  43186. set: function (value) {
  43187. var previousNeedCube = this.needCube();
  43188. this._direction = value;
  43189. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  43190. this._shadowGenerator.recreateShadowMap();
  43191. }
  43192. },
  43193. enumerable: true,
  43194. configurable: true
  43195. });
  43196. /**
  43197. * Returns the string "PointLight"
  43198. * @returns the class name
  43199. */
  43200. PointLight.prototype.getClassName = function () {
  43201. return "PointLight";
  43202. };
  43203. /**
  43204. * Returns the integer 0.
  43205. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43206. */
  43207. PointLight.prototype.getTypeID = function () {
  43208. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  43209. };
  43210. /**
  43211. * Specifies wether or not the shadowmap should be a cube texture.
  43212. * @returns true if the shadowmap needs to be a cube texture.
  43213. */
  43214. PointLight.prototype.needCube = function () {
  43215. return !this.direction;
  43216. };
  43217. /**
  43218. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  43219. * @param faceIndex The index of the face we are computed the direction to generate shadow
  43220. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  43221. */
  43222. PointLight.prototype.getShadowDirection = function (faceIndex) {
  43223. if (this.direction) {
  43224. return _super.prototype.getShadowDirection.call(this, faceIndex);
  43225. }
  43226. else {
  43227. switch (faceIndex) {
  43228. case 0:
  43229. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  43230. case 1:
  43231. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  43232. case 2:
  43233. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  43234. case 3:
  43235. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  43236. case 4:
  43237. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  43238. case 5:
  43239. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  43240. }
  43241. }
  43242. return BABYLON.Vector3.Zero();
  43243. };
  43244. /**
  43245. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  43246. * - fov = PI / 2
  43247. * - aspect ratio : 1.0
  43248. * - z-near and far equal to the active camera minZ and maxZ.
  43249. * Returns the PointLight.
  43250. */
  43251. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43252. var activeCamera = this.getScene().activeCamera;
  43253. if (!activeCamera) {
  43254. return;
  43255. }
  43256. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43257. };
  43258. PointLight.prototype._buildUniformLayout = function () {
  43259. this._uniformBuffer.addUniform("vLightData", 4);
  43260. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43261. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43262. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43263. this._uniformBuffer.addUniform("depthValues", 2);
  43264. this._uniformBuffer.create();
  43265. };
  43266. /**
  43267. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  43268. * @param effect The effect to update
  43269. * @param lightIndex The index of the light in the effect to update
  43270. * @returns The point light
  43271. */
  43272. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  43273. if (this.computeTransformedInformation()) {
  43274. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  43275. return this;
  43276. }
  43277. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  43278. return this;
  43279. };
  43280. __decorate([
  43281. BABYLON.serialize()
  43282. ], PointLight.prototype, "shadowAngle", null);
  43283. return PointLight;
  43284. }(BABYLON.ShadowLight));
  43285. BABYLON.PointLight = PointLight;
  43286. })(BABYLON || (BABYLON = {}));
  43287. //# sourceMappingURL=babylon.pointLight.js.map
  43288. var BABYLON;
  43289. (function (BABYLON) {
  43290. /**
  43291. * A directional light is defined by a direction (what a surprise!).
  43292. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  43293. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  43294. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43295. */
  43296. var DirectionalLight = /** @class */ (function (_super) {
  43297. __extends(DirectionalLight, _super);
  43298. /**
  43299. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  43300. * The directional light is emitted from everywhere in the given direction.
  43301. * It can cast shawdows.
  43302. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43303. * @param name The friendly name of the light
  43304. * @param direction The direction of the light
  43305. * @param scene The scene the light belongs to
  43306. */
  43307. function DirectionalLight(name, direction, scene) {
  43308. var _this = _super.call(this, name, scene) || this;
  43309. _this._shadowFrustumSize = 0;
  43310. _this._shadowOrthoScale = 0.5;
  43311. /**
  43312. * Automatically compute the projection matrix to best fit (including all the casters)
  43313. * on each frame.
  43314. */
  43315. _this.autoUpdateExtends = true;
  43316. // Cache
  43317. _this._orthoLeft = Number.MAX_VALUE;
  43318. _this._orthoRight = Number.MIN_VALUE;
  43319. _this._orthoTop = Number.MIN_VALUE;
  43320. _this._orthoBottom = Number.MAX_VALUE;
  43321. _this.position = direction.scale(-1.0);
  43322. _this.direction = direction;
  43323. return _this;
  43324. }
  43325. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  43326. /**
  43327. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  43328. */
  43329. get: function () {
  43330. return this._shadowFrustumSize;
  43331. },
  43332. /**
  43333. * Specifies a fix frustum size for the shadow generation.
  43334. */
  43335. set: function (value) {
  43336. this._shadowFrustumSize = value;
  43337. this.forceProjectionMatrixCompute();
  43338. },
  43339. enumerable: true,
  43340. configurable: true
  43341. });
  43342. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  43343. /**
  43344. * Gets the shadow projection scale against the optimal computed one.
  43345. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43346. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43347. */
  43348. get: function () {
  43349. return this._shadowOrthoScale;
  43350. },
  43351. /**
  43352. * Sets the shadow projection scale against the optimal computed one.
  43353. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  43354. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  43355. */
  43356. set: function (value) {
  43357. this._shadowOrthoScale = value;
  43358. this.forceProjectionMatrixCompute();
  43359. },
  43360. enumerable: true,
  43361. configurable: true
  43362. });
  43363. /**
  43364. * Returns the string "DirectionalLight".
  43365. * @return The class name
  43366. */
  43367. DirectionalLight.prototype.getClassName = function () {
  43368. return "DirectionalLight";
  43369. };
  43370. /**
  43371. * Returns the integer 1.
  43372. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43373. */
  43374. DirectionalLight.prototype.getTypeID = function () {
  43375. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  43376. };
  43377. /**
  43378. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  43379. * Returns the DirectionalLight Shadow projection matrix.
  43380. */
  43381. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43382. if (this.shadowFrustumSize > 0) {
  43383. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  43384. }
  43385. else {
  43386. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  43387. }
  43388. };
  43389. /**
  43390. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  43391. * Returns the DirectionalLight Shadow projection matrix.
  43392. */
  43393. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  43394. var activeCamera = this.getScene().activeCamera;
  43395. if (!activeCamera) {
  43396. return;
  43397. }
  43398. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  43399. };
  43400. /**
  43401. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  43402. * Returns the DirectionalLight Shadow projection matrix.
  43403. */
  43404. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43405. var activeCamera = this.getScene().activeCamera;
  43406. if (!activeCamera) {
  43407. return;
  43408. }
  43409. // Check extends
  43410. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  43411. var tempVector3 = BABYLON.Vector3.Zero();
  43412. this._orthoLeft = Number.MAX_VALUE;
  43413. this._orthoRight = Number.MIN_VALUE;
  43414. this._orthoTop = Number.MIN_VALUE;
  43415. this._orthoBottom = Number.MAX_VALUE;
  43416. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  43417. var mesh = renderList[meshIndex];
  43418. if (!mesh) {
  43419. continue;
  43420. }
  43421. var boundingInfo = mesh.getBoundingInfo();
  43422. var boundingBox = boundingInfo.boundingBox;
  43423. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  43424. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  43425. if (tempVector3.x < this._orthoLeft)
  43426. this._orthoLeft = tempVector3.x;
  43427. if (tempVector3.y < this._orthoBottom)
  43428. this._orthoBottom = tempVector3.y;
  43429. if (tempVector3.x > this._orthoRight)
  43430. this._orthoRight = tempVector3.x;
  43431. if (tempVector3.y > this._orthoTop)
  43432. this._orthoTop = tempVector3.y;
  43433. }
  43434. }
  43435. }
  43436. var xOffset = this._orthoRight - this._orthoLeft;
  43437. var yOffset = this._orthoTop - this._orthoBottom;
  43438. 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);
  43439. };
  43440. DirectionalLight.prototype._buildUniformLayout = function () {
  43441. this._uniformBuffer.addUniform("vLightData", 4);
  43442. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43443. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43444. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43445. this._uniformBuffer.addUniform("depthValues", 2);
  43446. this._uniformBuffer.create();
  43447. };
  43448. /**
  43449. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  43450. * @param effect The effect to update
  43451. * @param lightIndex The index of the light in the effect to update
  43452. * @returns The directional light
  43453. */
  43454. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  43455. if (this.computeTransformedInformation()) {
  43456. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  43457. return this;
  43458. }
  43459. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  43460. return this;
  43461. };
  43462. /**
  43463. * Gets the minZ used for shadow according to both the scene and the light.
  43464. *
  43465. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43466. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43467. * @param activeCamera The camera we are returning the min for
  43468. * @returns the depth min z
  43469. */
  43470. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  43471. return 1;
  43472. };
  43473. /**
  43474. * Gets the maxZ used for shadow according to both the scene and the light.
  43475. *
  43476. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43477. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43478. * @param activeCamera The camera we are returning the max for
  43479. * @returns the depth max z
  43480. */
  43481. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  43482. return 1;
  43483. };
  43484. __decorate([
  43485. BABYLON.serialize()
  43486. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  43487. __decorate([
  43488. BABYLON.serialize()
  43489. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  43490. __decorate([
  43491. BABYLON.serialize()
  43492. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  43493. return DirectionalLight;
  43494. }(BABYLON.ShadowLight));
  43495. BABYLON.DirectionalLight = DirectionalLight;
  43496. })(BABYLON || (BABYLON = {}));
  43497. //# sourceMappingURL=babylon.directionalLight.js.map
  43498. var BABYLON;
  43499. (function (BABYLON) {
  43500. /**
  43501. * A spot light is defined by a position, a direction, an angle, and an exponent.
  43502. * These values define a cone of light starting from the position, emitting toward the direction.
  43503. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  43504. * and the exponent defines the speed of the decay of the light with distance (reach).
  43505. * Documentation: https://doc.babylonjs.com/babylon101/lights
  43506. */
  43507. var SpotLight = /** @class */ (function (_super) {
  43508. __extends(SpotLight, _super);
  43509. /**
  43510. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  43511. * It can cast shadows.
  43512. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43513. * @param name The light friendly name
  43514. * @param position The position of the spot light in the scene
  43515. * @param direction The direction of the light in the scene
  43516. * @param angle The cone angle of the light in Radians
  43517. * @param exponent The light decay speed with the distance from the emission spot
  43518. * @param scene The scene the lights belongs to
  43519. */
  43520. function SpotLight(name, position, direction, angle, exponent, scene) {
  43521. var _this = _super.call(this, name, scene) || this;
  43522. _this._textureProjectionMatrix = BABYLON.Matrix.Zero();
  43523. _this.position = position;
  43524. _this.direction = direction;
  43525. _this.angle = angle;
  43526. _this.exponent = exponent;
  43527. return _this;
  43528. }
  43529. Object.defineProperty(SpotLight.prototype, "angle", {
  43530. get: function () {
  43531. return this._angle;
  43532. },
  43533. /**
  43534. * Sets the cone angle of the spot light in Radians.
  43535. */
  43536. set: function (value) {
  43537. this._angle = value;
  43538. this.forceProjectionMatrixCompute();
  43539. },
  43540. enumerable: true,
  43541. configurable: true
  43542. });
  43543. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  43544. get: function () {
  43545. return this._shadowAngleScale;
  43546. },
  43547. /**
  43548. * Allows scaling the angle of the light for shadow generation only.
  43549. */
  43550. set: function (value) {
  43551. this._shadowAngleScale = value;
  43552. this.forceProjectionMatrixCompute();
  43553. },
  43554. enumerable: true,
  43555. configurable: true
  43556. });
  43557. Object.defineProperty(SpotLight.prototype, "textureMatrix", {
  43558. get: function () {
  43559. return this._textureProjectionMatrix;
  43560. },
  43561. /**
  43562. * Allows setting the value of projection texture
  43563. */
  43564. set: function (value) {
  43565. this._textureProjectionMatrix = value;
  43566. },
  43567. enumerable: true,
  43568. configurable: true
  43569. });
  43570. Object.defineProperty(SpotLight.prototype, "light_near", {
  43571. get: function () {
  43572. return this._light_near;
  43573. },
  43574. /**
  43575. * Sets the near clip of the Spotlight for texture projection.
  43576. */
  43577. set: function (value) {
  43578. this._light_near = value;
  43579. this._computeTextureMatrix();
  43580. },
  43581. enumerable: true,
  43582. configurable: true
  43583. });
  43584. Object.defineProperty(SpotLight.prototype, "light_far", {
  43585. /**
  43586. * Gets the far clip of the Spotlight for texture projection.
  43587. */
  43588. get: function () {
  43589. return this._light_far;
  43590. },
  43591. /**
  43592. * Sets the far clip of the Spotlight for texture projection.
  43593. */
  43594. set: function (value) {
  43595. this._light_far = value;
  43596. },
  43597. enumerable: true,
  43598. configurable: true
  43599. });
  43600. ;
  43601. Object.defineProperty(SpotLight.prototype, "projectedLightTexture", {
  43602. /**
  43603. * Gets the projection texture of the light.
  43604. */
  43605. get: function () {
  43606. return this._projectedLightTexture;
  43607. },
  43608. /**
  43609. * Sets the projection texture of the light.
  43610. */
  43611. set: function (value) {
  43612. this._projectedLightTexture = value;
  43613. this._light_far = 1000.0;
  43614. this._light_near = 1e-6;
  43615. this._computeTextureMatrix();
  43616. },
  43617. enumerable: true,
  43618. configurable: true
  43619. });
  43620. /**
  43621. * Returns the string "SpotLight".
  43622. * @returns the class name
  43623. */
  43624. SpotLight.prototype.getClassName = function () {
  43625. return "SpotLight";
  43626. };
  43627. /**
  43628. * Returns the integer 2.
  43629. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  43630. */
  43631. SpotLight.prototype.getTypeID = function () {
  43632. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  43633. };
  43634. /**
  43635. * 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.
  43636. * Returns the SpotLight.
  43637. */
  43638. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43639. var activeCamera = this.getScene().activeCamera;
  43640. if (!activeCamera) {
  43641. return;
  43642. }
  43643. this._shadowAngleScale = this._shadowAngleScale || 1;
  43644. var angle = this._shadowAngleScale * this._angle;
  43645. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43646. };
  43647. /**
  43648. * Main function for light texture projection matrix computing.
  43649. */
  43650. SpotLight.prototype._computeTextureMatrix = function () {
  43651. var viewLightMatrix = BABYLON.Matrix.Zero();
  43652. BABYLON.Matrix.LookAtLHToRef(this.position, this.position.add(this.direction), BABYLON.Vector3.Up(), viewLightMatrix);
  43653. var light_far = this.light_far;
  43654. var light_near = this.light_near;
  43655. var P = light_far / (light_far - light_near);
  43656. var Q = -P * light_near;
  43657. var S = 1.0 / Math.tan(this._angle / 2.0);
  43658. var A = 1.0;
  43659. var projectionLightMatrix = BABYLON.Matrix.Zero();
  43660. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, projectionLightMatrix);
  43661. var scaleMatrix = BABYLON.Matrix.Zero();
  43662. BABYLON.Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0, scaleMatrix);
  43663. this._textureProjectionMatrix.copyFrom(viewLightMatrix);
  43664. this._textureProjectionMatrix.multiplyToRef(projectionLightMatrix, this._textureProjectionMatrix);
  43665. this._textureProjectionMatrix.multiplyToRef(scaleMatrix, this._textureProjectionMatrix);
  43666. };
  43667. SpotLight.prototype._buildUniformLayout = function () {
  43668. this._uniformBuffer.addUniform("vLightData", 4);
  43669. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43670. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43671. this._uniformBuffer.addUniform("vLightDirection", 3);
  43672. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43673. this._uniformBuffer.addUniform("depthValues", 2);
  43674. this._uniformBuffer.create();
  43675. };
  43676. /**
  43677. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  43678. * @param effect The effect to update
  43679. * @param lightIndex The index of the light in the effect to update
  43680. * @returns The spot light
  43681. */
  43682. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  43683. var normalizeDirection;
  43684. if (this.computeTransformedInformation()) {
  43685. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  43686. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  43687. }
  43688. else {
  43689. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  43690. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43691. }
  43692. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  43693. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._textureProjectionMatrix);
  43694. if (this.projectedLightTexture) {
  43695. effect.setTexture("projectionLightSampler" + lightIndex, this.projectedLightTexture);
  43696. }
  43697. return this;
  43698. };
  43699. /**
  43700. * Disposes the light and the associated resources.
  43701. */
  43702. SpotLight.prototype.dispose = function () {
  43703. _super.prototype.dispose.call(this);
  43704. if (this._projectedLightTexture) {
  43705. this._projectedLightTexture.dispose();
  43706. }
  43707. };
  43708. __decorate([
  43709. BABYLON.serialize()
  43710. /**
  43711. * Gets the cone angle of the spot light in Radians.
  43712. */
  43713. ], SpotLight.prototype, "angle", null);
  43714. __decorate([
  43715. BABYLON.serialize()
  43716. /**
  43717. * Allows scaling the angle of the light for shadow generation only.
  43718. */
  43719. ], SpotLight.prototype, "shadowAngleScale", null);
  43720. __decorate([
  43721. BABYLON.serialize()
  43722. ], SpotLight.prototype, "exponent", void 0);
  43723. __decorate([
  43724. BABYLON.serialize()
  43725. /**
  43726. * Allows reading the projecton texture
  43727. */
  43728. ], SpotLight.prototype, "textureMatrix", null);
  43729. __decorate([
  43730. BABYLON.serialize()
  43731. /**
  43732. * Gets the near clip of the Spotlight for texture projection.
  43733. */
  43734. ], SpotLight.prototype, "light_near", null);
  43735. __decorate([
  43736. BABYLON.serialize()
  43737. ], SpotLight.prototype, "light_far", null);
  43738. __decorate([
  43739. BABYLON.serializeAsTexture("projectedLightTexture")
  43740. ], SpotLight.prototype, "_projectedLightTexture", void 0);
  43741. return SpotLight;
  43742. }(BABYLON.ShadowLight));
  43743. BABYLON.SpotLight = SpotLight;
  43744. })(BABYLON || (BABYLON = {}));
  43745. //# sourceMappingURL=babylon.spotLight.js.map
  43746. var BABYLON;
  43747. (function (BABYLON) {
  43748. var AnimationRange = /** @class */ (function () {
  43749. function AnimationRange(name, from, to) {
  43750. this.name = name;
  43751. this.from = from;
  43752. this.to = to;
  43753. }
  43754. AnimationRange.prototype.clone = function () {
  43755. return new AnimationRange(this.name, this.from, this.to);
  43756. };
  43757. return AnimationRange;
  43758. }());
  43759. BABYLON.AnimationRange = AnimationRange;
  43760. /**
  43761. * Composed of a frame, and an action function
  43762. */
  43763. var AnimationEvent = /** @class */ (function () {
  43764. function AnimationEvent(frame, action, onlyOnce) {
  43765. this.frame = frame;
  43766. this.action = action;
  43767. this.onlyOnce = onlyOnce;
  43768. this.isDone = false;
  43769. }
  43770. return AnimationEvent;
  43771. }());
  43772. BABYLON.AnimationEvent = AnimationEvent;
  43773. var PathCursor = /** @class */ (function () {
  43774. function PathCursor(path) {
  43775. this.path = path;
  43776. this._onchange = new Array();
  43777. this.value = 0;
  43778. this.animations = new Array();
  43779. }
  43780. PathCursor.prototype.getPoint = function () {
  43781. var point = this.path.getPointAtLengthPosition(this.value);
  43782. return new BABYLON.Vector3(point.x, 0, point.y);
  43783. };
  43784. PathCursor.prototype.moveAhead = function (step) {
  43785. if (step === void 0) { step = 0.002; }
  43786. this.move(step);
  43787. return this;
  43788. };
  43789. PathCursor.prototype.moveBack = function (step) {
  43790. if (step === void 0) { step = 0.002; }
  43791. this.move(-step);
  43792. return this;
  43793. };
  43794. PathCursor.prototype.move = function (step) {
  43795. if (Math.abs(step) > 1) {
  43796. throw "step size should be less than 1.";
  43797. }
  43798. this.value += step;
  43799. this.ensureLimits();
  43800. this.raiseOnChange();
  43801. return this;
  43802. };
  43803. PathCursor.prototype.ensureLimits = function () {
  43804. while (this.value > 1) {
  43805. this.value -= 1;
  43806. }
  43807. while (this.value < 0) {
  43808. this.value += 1;
  43809. }
  43810. return this;
  43811. };
  43812. // used by animation engine
  43813. PathCursor.prototype.raiseOnChange = function () {
  43814. var _this = this;
  43815. this._onchange.forEach(function (f) { return f(_this); });
  43816. return this;
  43817. };
  43818. PathCursor.prototype.onchange = function (f) {
  43819. this._onchange.push(f);
  43820. return this;
  43821. };
  43822. return PathCursor;
  43823. }());
  43824. BABYLON.PathCursor = PathCursor;
  43825. var AnimationKeyInterpolation;
  43826. (function (AnimationKeyInterpolation) {
  43827. /**
  43828. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  43829. */
  43830. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  43831. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  43832. var Animation = /** @class */ (function () {
  43833. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  43834. this.name = name;
  43835. this.targetProperty = targetProperty;
  43836. this.framePerSecond = framePerSecond;
  43837. this.dataType = dataType;
  43838. this.loopMode = loopMode;
  43839. this.enableBlending = enableBlending;
  43840. this._runtimeAnimations = new Array();
  43841. // The set of event that will be linked to this animation
  43842. this._events = new Array();
  43843. this.blendingSpeed = 0.01;
  43844. this._ranges = {};
  43845. this.targetPropertyPath = targetProperty.split(".");
  43846. this.dataType = dataType;
  43847. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  43848. }
  43849. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  43850. var dataType = undefined;
  43851. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  43852. dataType = Animation.ANIMATIONTYPE_FLOAT;
  43853. }
  43854. else if (from instanceof BABYLON.Quaternion) {
  43855. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  43856. }
  43857. else if (from instanceof BABYLON.Vector3) {
  43858. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  43859. }
  43860. else if (from instanceof BABYLON.Vector2) {
  43861. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  43862. }
  43863. else if (from instanceof BABYLON.Color3) {
  43864. dataType = Animation.ANIMATIONTYPE_COLOR3;
  43865. }
  43866. else if (from instanceof BABYLON.Size) {
  43867. dataType = Animation.ANIMATIONTYPE_SIZE;
  43868. }
  43869. if (dataType == undefined) {
  43870. return null;
  43871. }
  43872. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  43873. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  43874. animation.setKeys(keys);
  43875. if (easingFunction !== undefined) {
  43876. animation.setEasingFunction(easingFunction);
  43877. }
  43878. return animation;
  43879. };
  43880. /**
  43881. * Sets up an animation.
  43882. * @param property the property to animate
  43883. * @param animationType the animation type to apply
  43884. * @param easingFunction the easing function used in the animation
  43885. * @returns The created animation
  43886. */
  43887. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  43888. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  43889. animation.setEasingFunction(easingFunction);
  43890. return animation;
  43891. };
  43892. /**
  43893. * Create and start an animation on a node
  43894. * @param {string} name defines the name of the global animation that will be run on all nodes
  43895. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43896. * @param {string} targetProperty defines property to animate
  43897. * @param {number} framePerSecond defines the number of frame per second yo use
  43898. * @param {number} totalFrame defines the number of frames in total
  43899. * @param {any} from defines the initial value
  43900. * @param {any} to defines the final value
  43901. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43902. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43903. * @param onAnimationEnd defines the callback to call when animation end
  43904. * @returns the animatable created for this animation
  43905. */
  43906. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43907. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43908. if (!animation) {
  43909. return null;
  43910. }
  43911. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43912. };
  43913. /**
  43914. * Create and start an animation on a node and its descendants
  43915. * @param {string} name defines the name of the global animation that will be run on all nodes
  43916. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43917. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  43918. * @param {string} targetProperty defines property to animate
  43919. * @param {number} framePerSecond defines the number of frame per second yo use
  43920. * @param {number} totalFrame defines the number of frames in total
  43921. * @param {any} from defines the initial value
  43922. * @param {any} to defines the final value
  43923. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43924. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43925. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  43926. * @returns the list of animatables created for all nodes
  43927. * @example https://www.babylonjs-playground.com/#MH0VLI
  43928. */
  43929. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43930. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43931. if (!animation) {
  43932. return null;
  43933. }
  43934. var scene = node.getScene();
  43935. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43936. };
  43937. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43938. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43939. if (!animation) {
  43940. return null;
  43941. }
  43942. node.animations.push(animation);
  43943. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43944. };
  43945. /**
  43946. * Transition property of the Camera to the target Value.
  43947. * @param property The property to transition
  43948. * @param targetValue The target Value of the property
  43949. * @param host The object where the property to animate belongs
  43950. * @param scene Scene used to run the animation
  43951. * @param frameRate Framerate (in frame/s) to use
  43952. * @param transition The transition type we want to use
  43953. * @param duration The duration of the animation, in milliseconds
  43954. * @param onAnimationEnd Call back trigger at the end of the animation.
  43955. */
  43956. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43957. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43958. if (duration <= 0) {
  43959. host[property] = targetValue;
  43960. if (onAnimationEnd) {
  43961. onAnimationEnd();
  43962. }
  43963. return null;
  43964. }
  43965. var endFrame = frameRate * (duration / 1000);
  43966. transition.setKeys([{
  43967. frame: 0,
  43968. value: host[property].clone ? host[property].clone() : host[property]
  43969. },
  43970. {
  43971. frame: endFrame,
  43972. value: targetValue
  43973. }]);
  43974. if (!host.animations) {
  43975. host.animations = [];
  43976. }
  43977. host.animations.push(transition);
  43978. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43979. animation.onAnimationEnd = onAnimationEnd;
  43980. return animation;
  43981. };
  43982. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43983. /**
  43984. * Return the array of runtime animations currently using this animation
  43985. */
  43986. get: function () {
  43987. return this._runtimeAnimations;
  43988. },
  43989. enumerable: true,
  43990. configurable: true
  43991. });
  43992. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43993. get: function () {
  43994. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43995. var runtimeAnimation = _a[_i];
  43996. if (!runtimeAnimation.isStopped) {
  43997. return true;
  43998. }
  43999. }
  44000. return false;
  44001. },
  44002. enumerable: true,
  44003. configurable: true
  44004. });
  44005. // Methods
  44006. /**
  44007. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  44008. */
  44009. Animation.prototype.toString = function (fullDetails) {
  44010. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  44011. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  44012. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  44013. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  44014. if (fullDetails) {
  44015. ret += ", Ranges: {";
  44016. var first = true;
  44017. for (var name in this._ranges) {
  44018. if (first) {
  44019. ret += ", ";
  44020. first = false;
  44021. }
  44022. ret += name;
  44023. }
  44024. ret += "}";
  44025. }
  44026. return ret;
  44027. };
  44028. /**
  44029. * Add an event to this animation.
  44030. */
  44031. Animation.prototype.addEvent = function (event) {
  44032. this._events.push(event);
  44033. };
  44034. /**
  44035. * Remove all events found at the given frame
  44036. * @param frame
  44037. */
  44038. Animation.prototype.removeEvents = function (frame) {
  44039. for (var index = 0; index < this._events.length; index++) {
  44040. if (this._events[index].frame === frame) {
  44041. this._events.splice(index, 1);
  44042. index--;
  44043. }
  44044. }
  44045. };
  44046. Animation.prototype.getEvents = function () {
  44047. return this._events;
  44048. };
  44049. Animation.prototype.createRange = function (name, from, to) {
  44050. // check name not already in use; could happen for bones after serialized
  44051. if (!this._ranges[name]) {
  44052. this._ranges[name] = new AnimationRange(name, from, to);
  44053. }
  44054. };
  44055. Animation.prototype.deleteRange = function (name, deleteFrames) {
  44056. if (deleteFrames === void 0) { deleteFrames = true; }
  44057. var range = this._ranges[name];
  44058. if (!range) {
  44059. return;
  44060. }
  44061. if (deleteFrames) {
  44062. var from = range.from;
  44063. var to = range.to;
  44064. // this loop MUST go high to low for multiple splices to work
  44065. for (var key = this._keys.length - 1; key >= 0; key--) {
  44066. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  44067. this._keys.splice(key, 1);
  44068. }
  44069. }
  44070. }
  44071. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  44072. };
  44073. Animation.prototype.getRange = function (name) {
  44074. return this._ranges[name];
  44075. };
  44076. Animation.prototype.getKeys = function () {
  44077. return this._keys;
  44078. };
  44079. Animation.prototype.getHighestFrame = function () {
  44080. var ret = 0;
  44081. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  44082. if (ret < this._keys[key].frame) {
  44083. ret = this._keys[key].frame;
  44084. }
  44085. }
  44086. return ret;
  44087. };
  44088. Animation.prototype.getEasingFunction = function () {
  44089. return this._easingFunction;
  44090. };
  44091. Animation.prototype.setEasingFunction = function (easingFunction) {
  44092. this._easingFunction = easingFunction;
  44093. };
  44094. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  44095. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  44096. };
  44097. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44098. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44099. };
  44100. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  44101. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  44102. };
  44103. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44104. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  44105. };
  44106. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  44107. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  44108. };
  44109. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44110. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44111. };
  44112. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  44113. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  44114. };
  44115. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  44116. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  44117. };
  44118. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  44119. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  44120. };
  44121. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  44122. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  44123. };
  44124. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  44125. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  44126. };
  44127. Animation.prototype.clone = function () {
  44128. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  44129. clone.enableBlending = this.enableBlending;
  44130. clone.blendingSpeed = this.blendingSpeed;
  44131. if (this._keys) {
  44132. clone.setKeys(this._keys);
  44133. }
  44134. if (this._ranges) {
  44135. clone._ranges = {};
  44136. for (var name in this._ranges) {
  44137. var range = this._ranges[name];
  44138. if (!range) {
  44139. continue;
  44140. }
  44141. clone._ranges[name] = range.clone();
  44142. }
  44143. }
  44144. return clone;
  44145. };
  44146. Animation.prototype.setKeys = function (values) {
  44147. this._keys = values.slice(0);
  44148. };
  44149. Animation.prototype.serialize = function () {
  44150. var serializationObject = {};
  44151. serializationObject.name = this.name;
  44152. serializationObject.property = this.targetProperty;
  44153. serializationObject.framePerSecond = this.framePerSecond;
  44154. serializationObject.dataType = this.dataType;
  44155. serializationObject.loopBehavior = this.loopMode;
  44156. serializationObject.enableBlending = this.enableBlending;
  44157. serializationObject.blendingSpeed = this.blendingSpeed;
  44158. var dataType = this.dataType;
  44159. serializationObject.keys = [];
  44160. var keys = this.getKeys();
  44161. for (var index = 0; index < keys.length; index++) {
  44162. var animationKey = keys[index];
  44163. var key = {};
  44164. key.frame = animationKey.frame;
  44165. switch (dataType) {
  44166. case Animation.ANIMATIONTYPE_FLOAT:
  44167. key.values = [animationKey.value];
  44168. break;
  44169. case Animation.ANIMATIONTYPE_QUATERNION:
  44170. case Animation.ANIMATIONTYPE_MATRIX:
  44171. case Animation.ANIMATIONTYPE_VECTOR3:
  44172. case Animation.ANIMATIONTYPE_COLOR3:
  44173. key.values = animationKey.value.asArray();
  44174. break;
  44175. }
  44176. serializationObject.keys.push(key);
  44177. }
  44178. serializationObject.ranges = [];
  44179. for (var name in this._ranges) {
  44180. var source = this._ranges[name];
  44181. if (!source) {
  44182. continue;
  44183. }
  44184. var range = {};
  44185. range.name = name;
  44186. range.from = source.from;
  44187. range.to = source.to;
  44188. serializationObject.ranges.push(range);
  44189. }
  44190. return serializationObject;
  44191. };
  44192. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  44193. get: function () {
  44194. return Animation._ANIMATIONTYPE_FLOAT;
  44195. },
  44196. enumerable: true,
  44197. configurable: true
  44198. });
  44199. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  44200. get: function () {
  44201. return Animation._ANIMATIONTYPE_VECTOR3;
  44202. },
  44203. enumerable: true,
  44204. configurable: true
  44205. });
  44206. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  44207. get: function () {
  44208. return Animation._ANIMATIONTYPE_VECTOR2;
  44209. },
  44210. enumerable: true,
  44211. configurable: true
  44212. });
  44213. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  44214. get: function () {
  44215. return Animation._ANIMATIONTYPE_SIZE;
  44216. },
  44217. enumerable: true,
  44218. configurable: true
  44219. });
  44220. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  44221. get: function () {
  44222. return Animation._ANIMATIONTYPE_QUATERNION;
  44223. },
  44224. enumerable: true,
  44225. configurable: true
  44226. });
  44227. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  44228. get: function () {
  44229. return Animation._ANIMATIONTYPE_MATRIX;
  44230. },
  44231. enumerable: true,
  44232. configurable: true
  44233. });
  44234. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  44235. get: function () {
  44236. return Animation._ANIMATIONTYPE_COLOR3;
  44237. },
  44238. enumerable: true,
  44239. configurable: true
  44240. });
  44241. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  44242. get: function () {
  44243. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  44244. },
  44245. enumerable: true,
  44246. configurable: true
  44247. });
  44248. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  44249. get: function () {
  44250. return Animation._ANIMATIONLOOPMODE_CYCLE;
  44251. },
  44252. enumerable: true,
  44253. configurable: true
  44254. });
  44255. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  44256. get: function () {
  44257. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  44258. },
  44259. enumerable: true,
  44260. configurable: true
  44261. });
  44262. Animation.Parse = function (parsedAnimation) {
  44263. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  44264. var dataType = parsedAnimation.dataType;
  44265. var keys = [];
  44266. var data;
  44267. var index;
  44268. if (parsedAnimation.enableBlending) {
  44269. animation.enableBlending = parsedAnimation.enableBlending;
  44270. }
  44271. if (parsedAnimation.blendingSpeed) {
  44272. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  44273. }
  44274. for (index = 0; index < parsedAnimation.keys.length; index++) {
  44275. var key = parsedAnimation.keys[index];
  44276. var inTangent;
  44277. var outTangent;
  44278. switch (dataType) {
  44279. case Animation.ANIMATIONTYPE_FLOAT:
  44280. data = key.values[0];
  44281. if (key.values.length >= 1) {
  44282. inTangent = key.values[1];
  44283. }
  44284. if (key.values.length >= 2) {
  44285. outTangent = key.values[2];
  44286. }
  44287. break;
  44288. case Animation.ANIMATIONTYPE_QUATERNION:
  44289. data = BABYLON.Quaternion.FromArray(key.values);
  44290. if (key.values.length >= 8) {
  44291. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  44292. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  44293. inTangent = _inTangent;
  44294. }
  44295. }
  44296. if (key.values.length >= 12) {
  44297. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  44298. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  44299. outTangent = _outTangent;
  44300. }
  44301. }
  44302. break;
  44303. case Animation.ANIMATIONTYPE_MATRIX:
  44304. data = BABYLON.Matrix.FromArray(key.values);
  44305. break;
  44306. case Animation.ANIMATIONTYPE_COLOR3:
  44307. data = BABYLON.Color3.FromArray(key.values);
  44308. break;
  44309. case Animation.ANIMATIONTYPE_VECTOR3:
  44310. default:
  44311. data = BABYLON.Vector3.FromArray(key.values);
  44312. break;
  44313. }
  44314. var keyData = {};
  44315. keyData.frame = key.frame;
  44316. keyData.value = data;
  44317. if (inTangent != undefined) {
  44318. keyData.inTangent = inTangent;
  44319. }
  44320. if (outTangent != undefined) {
  44321. keyData.outTangent = outTangent;
  44322. }
  44323. keys.push(keyData);
  44324. }
  44325. animation.setKeys(keys);
  44326. if (parsedAnimation.ranges) {
  44327. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  44328. data = parsedAnimation.ranges[index];
  44329. animation.createRange(data.name, data.from, data.to);
  44330. }
  44331. }
  44332. return animation;
  44333. };
  44334. Animation.AppendSerializedAnimations = function (source, destination) {
  44335. if (source.animations) {
  44336. destination.animations = [];
  44337. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  44338. var animation = source.animations[animationIndex];
  44339. destination.animations.push(animation.serialize());
  44340. }
  44341. }
  44342. };
  44343. Animation.AllowMatricesInterpolation = false;
  44344. // Statics
  44345. Animation._ANIMATIONTYPE_FLOAT = 0;
  44346. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  44347. Animation._ANIMATIONTYPE_QUATERNION = 2;
  44348. Animation._ANIMATIONTYPE_MATRIX = 3;
  44349. Animation._ANIMATIONTYPE_COLOR3 = 4;
  44350. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  44351. Animation._ANIMATIONTYPE_SIZE = 6;
  44352. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  44353. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  44354. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  44355. return Animation;
  44356. }());
  44357. BABYLON.Animation = Animation;
  44358. })(BABYLON || (BABYLON = {}));
  44359. //# sourceMappingURL=babylon.animation.js.map
  44360. var BABYLON;
  44361. (function (BABYLON) {
  44362. /**
  44363. * This class defines the direct association between an animation and a target
  44364. */
  44365. var TargetedAnimation = /** @class */ (function () {
  44366. function TargetedAnimation() {
  44367. }
  44368. return TargetedAnimation;
  44369. }());
  44370. BABYLON.TargetedAnimation = TargetedAnimation;
  44371. /**
  44372. * Use this class to create coordinated animations on multiple targets
  44373. */
  44374. var AnimationGroup = /** @class */ (function () {
  44375. function AnimationGroup(name, scene) {
  44376. if (scene === void 0) { scene = null; }
  44377. this.name = name;
  44378. this._targetedAnimations = new Array();
  44379. this._animatables = new Array();
  44380. this._from = Number.MAX_VALUE;
  44381. this._to = -Number.MAX_VALUE;
  44382. this._speedRatio = 1;
  44383. this.onAnimationEndObservable = new BABYLON.Observable();
  44384. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44385. this._scene.animationGroups.push(this);
  44386. }
  44387. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  44388. /**
  44389. * Define if the animations are started
  44390. */
  44391. get: function () {
  44392. return this._isStarted;
  44393. },
  44394. enumerable: true,
  44395. configurable: true
  44396. });
  44397. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  44398. /**
  44399. * Gets or sets the speed ratio to use for all animations
  44400. */
  44401. get: function () {
  44402. return this._speedRatio;
  44403. },
  44404. /**
  44405. * Gets or sets the speed ratio to use for all animations
  44406. */
  44407. set: function (value) {
  44408. if (this._speedRatio === value) {
  44409. return;
  44410. }
  44411. this._speedRatio = value;
  44412. for (var index = 0; index < this._animatables.length; index++) {
  44413. var animatable = this._animatables[index];
  44414. animatable.speedRatio = this._speedRatio;
  44415. }
  44416. },
  44417. enumerable: true,
  44418. configurable: true
  44419. });
  44420. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  44421. /**
  44422. * Gets the targeted animations for this animation group
  44423. */
  44424. get: function () {
  44425. return this._targetedAnimations;
  44426. },
  44427. enumerable: true,
  44428. configurable: true
  44429. });
  44430. /**
  44431. * Add an animation (with its target) in the group
  44432. * @param animation defines the animation we want to add
  44433. * @param target defines the target of the animation
  44434. * @returns the {BABYLON.TargetedAnimation} object
  44435. */
  44436. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  44437. var targetedAnimation = {
  44438. animation: animation,
  44439. target: target
  44440. };
  44441. var keys = animation.getKeys();
  44442. if (this._from > keys[0].frame) {
  44443. this._from = keys[0].frame;
  44444. }
  44445. if (this._to < keys[keys.length - 1].frame) {
  44446. this._to = keys[keys.length - 1].frame;
  44447. }
  44448. this._targetedAnimations.push(targetedAnimation);
  44449. return targetedAnimation;
  44450. };
  44451. /**
  44452. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  44453. * It can add constant keys at begin or end
  44454. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  44455. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  44456. */
  44457. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  44458. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  44459. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  44460. beginFrame = Math.max(beginFrame, this._from);
  44461. endFrame = Math.min(endFrame, this._to);
  44462. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44463. var targetedAnimation = this._targetedAnimations[index];
  44464. var keys = targetedAnimation.animation.getKeys();
  44465. var startKey = keys[0];
  44466. var endKey = keys[keys.length - 1];
  44467. if (startKey.frame > beginFrame) {
  44468. var newKey = {
  44469. frame: beginFrame,
  44470. value: startKey.value,
  44471. inTangent: startKey.inTangent,
  44472. outTangent: startKey.outTangent,
  44473. interpolation: startKey.interpolation
  44474. };
  44475. keys.splice(0, 0, newKey);
  44476. }
  44477. if (endKey.frame < endFrame) {
  44478. var newKey = {
  44479. frame: endFrame,
  44480. value: endKey.value,
  44481. inTangent: endKey.outTangent,
  44482. outTangent: endKey.outTangent,
  44483. interpolation: endKey.interpolation
  44484. };
  44485. keys.push(newKey);
  44486. }
  44487. }
  44488. return this;
  44489. };
  44490. /**
  44491. * Start all animations on given targets
  44492. * @param loop defines if animations must loop
  44493. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  44494. */
  44495. AnimationGroup.prototype.start = function (loop, speedRatio) {
  44496. var _this = this;
  44497. if (loop === void 0) { loop = false; }
  44498. if (speedRatio === void 0) { speedRatio = 1; }
  44499. if (this._isStarted || this._targetedAnimations.length === 0) {
  44500. return this;
  44501. }
  44502. var _loop_1 = function () {
  44503. var targetedAnimation = this_1._targetedAnimations[index];
  44504. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  44505. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  44506. }));
  44507. };
  44508. var this_1 = this;
  44509. for (var index = 0; index < this._targetedAnimations.length; index++) {
  44510. _loop_1();
  44511. }
  44512. this._speedRatio = speedRatio;
  44513. this._isStarted = true;
  44514. return this;
  44515. };
  44516. /**
  44517. * Pause all animations
  44518. */
  44519. AnimationGroup.prototype.pause = function () {
  44520. if (!this._isStarted) {
  44521. return this;
  44522. }
  44523. for (var index = 0; index < this._animatables.length; index++) {
  44524. var animatable = this._animatables[index];
  44525. animatable.pause();
  44526. }
  44527. return this;
  44528. };
  44529. /**
  44530. * Play all animations to initial state
  44531. * This function will start() the animations if they were not started or will restart() them if they were paused
  44532. * @param loop defines if animations must loop
  44533. */
  44534. AnimationGroup.prototype.play = function (loop) {
  44535. if (this.isStarted) {
  44536. if (loop !== undefined) {
  44537. for (var index = 0; index < this._animatables.length; index++) {
  44538. var animatable = this._animatables[index];
  44539. animatable.loopAnimation = loop;
  44540. }
  44541. }
  44542. this.restart();
  44543. }
  44544. else {
  44545. this.start(loop, this._speedRatio);
  44546. }
  44547. return this;
  44548. };
  44549. /**
  44550. * Reset all animations to initial state
  44551. */
  44552. AnimationGroup.prototype.reset = function () {
  44553. if (!this._isStarted) {
  44554. return this;
  44555. }
  44556. for (var index = 0; index < this._animatables.length; index++) {
  44557. var animatable = this._animatables[index];
  44558. animatable.reset();
  44559. }
  44560. return this;
  44561. };
  44562. /**
  44563. * Restart animations from key 0
  44564. */
  44565. AnimationGroup.prototype.restart = function () {
  44566. if (!this._isStarted) {
  44567. return this;
  44568. }
  44569. for (var index = 0; index < this._animatables.length; index++) {
  44570. var animatable = this._animatables[index];
  44571. animatable.restart();
  44572. }
  44573. return this;
  44574. };
  44575. /**
  44576. * Stop all animations
  44577. */
  44578. AnimationGroup.prototype.stop = function () {
  44579. if (!this._isStarted) {
  44580. return this;
  44581. }
  44582. for (var index = 0; index < this._animatables.length; index++) {
  44583. var animatable = this._animatables[index];
  44584. animatable.stop();
  44585. }
  44586. this._isStarted = false;
  44587. return this;
  44588. };
  44589. /**
  44590. * Dispose all associated resources
  44591. */
  44592. AnimationGroup.prototype.dispose = function () {
  44593. this._targetedAnimations = [];
  44594. this._animatables = [];
  44595. var index = this._scene.animationGroups.indexOf(this);
  44596. if (index > -1) {
  44597. this._scene.animationGroups.splice(index, 1);
  44598. }
  44599. };
  44600. return AnimationGroup;
  44601. }());
  44602. BABYLON.AnimationGroup = AnimationGroup;
  44603. })(BABYLON || (BABYLON = {}));
  44604. //# sourceMappingURL=babylon.animationGroup.js.map
  44605. var BABYLON;
  44606. (function (BABYLON) {
  44607. var RuntimeAnimation = /** @class */ (function () {
  44608. function RuntimeAnimation(target, animation) {
  44609. this._offsetsCache = {};
  44610. this._highLimitsCache = {};
  44611. this._stopped = false;
  44612. this._blendingFactor = 0;
  44613. this._ratioOffset = 0;
  44614. this._animation = animation;
  44615. this._target = target;
  44616. animation._runtimeAnimations.push(this);
  44617. }
  44618. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  44619. get: function () {
  44620. return this._animation;
  44621. },
  44622. enumerable: true,
  44623. configurable: true
  44624. });
  44625. RuntimeAnimation.prototype.reset = function () {
  44626. this._offsetsCache = {};
  44627. this._highLimitsCache = {};
  44628. this.currentFrame = 0;
  44629. this._blendingFactor = 0;
  44630. this._originalBlendValue = null;
  44631. };
  44632. RuntimeAnimation.prototype.isStopped = function () {
  44633. return this._stopped;
  44634. };
  44635. RuntimeAnimation.prototype.dispose = function () {
  44636. var index = this._animation.runtimeAnimations.indexOf(this);
  44637. if (index > -1) {
  44638. this._animation.runtimeAnimations.splice(index, 1);
  44639. }
  44640. };
  44641. RuntimeAnimation.prototype._getKeyValue = function (value) {
  44642. if (typeof value === "function") {
  44643. return value();
  44644. }
  44645. return value;
  44646. };
  44647. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  44648. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  44649. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  44650. }
  44651. this.currentFrame = currentFrame;
  44652. var keys = this._animation.getKeys();
  44653. // Try to get a hash to find the right key
  44654. 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));
  44655. if (keys[startKeyIndex].frame >= currentFrame) {
  44656. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  44657. startKeyIndex--;
  44658. }
  44659. }
  44660. for (var key = startKeyIndex; key < keys.length; key++) {
  44661. var endKey = keys[key + 1];
  44662. if (endKey.frame >= currentFrame) {
  44663. var startKey = keys[key];
  44664. var startValue = this._getKeyValue(startKey.value);
  44665. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  44666. return startValue;
  44667. }
  44668. var endValue = this._getKeyValue(endKey.value);
  44669. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  44670. var frameDelta = endKey.frame - startKey.frame;
  44671. // gradient : percent of currentFrame between the frame inf and the frame sup
  44672. var gradient = (currentFrame - startKey.frame) / frameDelta;
  44673. // check for easingFunction and correction of gradient
  44674. var easingFunction = this._animation.getEasingFunction();
  44675. if (easingFunction != null) {
  44676. gradient = easingFunction.ease(gradient);
  44677. }
  44678. switch (this._animation.dataType) {
  44679. // Float
  44680. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44681. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  44682. switch (loopMode) {
  44683. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44684. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44685. return floatValue;
  44686. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44687. return offsetValue * repeatCount + floatValue;
  44688. }
  44689. break;
  44690. // Quaternion
  44691. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44692. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  44693. switch (loopMode) {
  44694. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44695. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44696. return quatValue;
  44697. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44698. return quatValue.add(offsetValue.scale(repeatCount));
  44699. }
  44700. return quatValue;
  44701. // Vector3
  44702. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44703. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  44704. switch (loopMode) {
  44705. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44706. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44707. return vec3Value;
  44708. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44709. return vec3Value.add(offsetValue.scale(repeatCount));
  44710. }
  44711. // Vector2
  44712. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44713. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  44714. switch (loopMode) {
  44715. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44716. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44717. return vec2Value;
  44718. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44719. return vec2Value.add(offsetValue.scale(repeatCount));
  44720. }
  44721. // Size
  44722. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44723. switch (loopMode) {
  44724. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44725. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44726. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  44727. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44728. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44729. }
  44730. // Color3
  44731. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44732. switch (loopMode) {
  44733. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44734. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44735. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  44736. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44737. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44738. }
  44739. // Matrix
  44740. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  44741. switch (loopMode) {
  44742. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44743. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44744. if (BABYLON.Animation.AllowMatricesInterpolation) {
  44745. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  44746. }
  44747. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44748. return startValue;
  44749. }
  44750. default:
  44751. break;
  44752. }
  44753. break;
  44754. }
  44755. }
  44756. return this._getKeyValue(keys[keys.length - 1].value);
  44757. };
  44758. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  44759. if (blend === void 0) { blend = false; }
  44760. // Set value
  44761. var path;
  44762. var destination;
  44763. var targetPropertyPath = this._animation.targetPropertyPath;
  44764. if (targetPropertyPath.length > 1) {
  44765. var property = this._target[targetPropertyPath[0]];
  44766. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44767. property = property[targetPropertyPath[index]];
  44768. }
  44769. path = targetPropertyPath[targetPropertyPath.length - 1];
  44770. destination = property;
  44771. }
  44772. else {
  44773. path = targetPropertyPath[0];
  44774. destination = this._target;
  44775. }
  44776. // Blending
  44777. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  44778. if (!this._originalBlendValue) {
  44779. if (destination[path].clone) {
  44780. this._originalBlendValue = destination[path].clone();
  44781. }
  44782. else {
  44783. this._originalBlendValue = destination[path];
  44784. }
  44785. }
  44786. if (this._originalBlendValue.prototype) {
  44787. if (this._originalBlendValue.prototype.Lerp) {
  44788. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  44789. }
  44790. else {
  44791. destination[path] = currentValue;
  44792. }
  44793. }
  44794. else if (this._originalBlendValue.m) {
  44795. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  44796. }
  44797. else {
  44798. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  44799. }
  44800. this._blendingFactor += this._animation.blendingSpeed;
  44801. }
  44802. else {
  44803. destination[path] = currentValue;
  44804. }
  44805. if (this._target.markAsDirty) {
  44806. this._target.markAsDirty(this._animation.targetProperty);
  44807. }
  44808. };
  44809. RuntimeAnimation.prototype.goToFrame = function (frame) {
  44810. var keys = this._animation.getKeys();
  44811. if (frame < keys[0].frame) {
  44812. frame = keys[0].frame;
  44813. }
  44814. else if (frame > keys[keys.length - 1].frame) {
  44815. frame = keys[keys.length - 1].frame;
  44816. }
  44817. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  44818. this.setValue(currentValue);
  44819. };
  44820. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  44821. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  44822. this._ratioOffset = this._previousRatio - newRatio;
  44823. };
  44824. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  44825. if (blend === void 0) { blend = false; }
  44826. var targetPropertyPath = this._animation.targetPropertyPath;
  44827. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  44828. this._stopped = true;
  44829. return false;
  44830. }
  44831. var returnValue = true;
  44832. var keys = this._animation.getKeys();
  44833. // Adding a start key at frame 0 if missing
  44834. if (keys[0].frame !== 0) {
  44835. var newKey = { frame: 0, value: keys[0].value };
  44836. keys.splice(0, 0, newKey);
  44837. }
  44838. // Check limits
  44839. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  44840. from = keys[0].frame;
  44841. }
  44842. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  44843. to = keys[keys.length - 1].frame;
  44844. }
  44845. //to and from cannot be the same key
  44846. if (from === to) {
  44847. if (from > keys[0].frame) {
  44848. from--;
  44849. }
  44850. else if (to < keys[keys.length - 1].frame) {
  44851. to++;
  44852. }
  44853. }
  44854. // Compute ratio
  44855. var range = to - from;
  44856. var offsetValue;
  44857. // ratio represents the frame delta between from and to
  44858. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  44859. var highLimitValue = 0;
  44860. this._previousDelay = delay;
  44861. this._previousRatio = ratio;
  44862. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  44863. returnValue = false;
  44864. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  44865. }
  44866. else {
  44867. // Get max value if required
  44868. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  44869. var keyOffset = to.toString() + from.toString();
  44870. if (!this._offsetsCache[keyOffset]) {
  44871. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44872. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44873. switch (this._animation.dataType) {
  44874. // Float
  44875. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44876. this._offsetsCache[keyOffset] = toValue - fromValue;
  44877. break;
  44878. // Quaternion
  44879. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44880. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44881. break;
  44882. // Vector3
  44883. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44884. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44885. // Vector2
  44886. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44887. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44888. // Size
  44889. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44890. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44891. // Color3
  44892. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44893. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44894. default:
  44895. break;
  44896. }
  44897. this._highLimitsCache[keyOffset] = toValue;
  44898. }
  44899. highLimitValue = this._highLimitsCache[keyOffset];
  44900. offsetValue = this._offsetsCache[keyOffset];
  44901. }
  44902. }
  44903. if (offsetValue === undefined) {
  44904. switch (this._animation.dataType) {
  44905. // Float
  44906. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44907. offsetValue = 0;
  44908. break;
  44909. // Quaternion
  44910. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44911. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  44912. break;
  44913. // Vector3
  44914. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44915. offsetValue = BABYLON.Vector3.Zero();
  44916. break;
  44917. // Vector2
  44918. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44919. offsetValue = BABYLON.Vector2.Zero();
  44920. break;
  44921. // Size
  44922. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44923. offsetValue = BABYLON.Size.Zero();
  44924. break;
  44925. // Color3
  44926. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44927. offsetValue = BABYLON.Color3.Black();
  44928. }
  44929. }
  44930. // Compute value
  44931. var repeatCount = (ratio / range) >> 0;
  44932. var currentFrame = returnValue ? from + ratio % range : to;
  44933. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44934. // Set value
  44935. this.setValue(currentValue);
  44936. // Check events
  44937. var events = this._animation.getEvents();
  44938. for (var index = 0; index < events.length; index++) {
  44939. // Make sure current frame has passed event frame and that event frame is within the current range
  44940. // Also, handle both forward and reverse animations
  44941. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44942. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44943. var event = events[index];
  44944. if (!event.isDone) {
  44945. // If event should be done only once, remove it.
  44946. if (event.onlyOnce) {
  44947. events.splice(index, 1);
  44948. index--;
  44949. }
  44950. event.isDone = true;
  44951. event.action();
  44952. } // Don't do anything if the event has already be done.
  44953. }
  44954. else if (events[index].isDone && !events[index].onlyOnce) {
  44955. // reset event, the animation is looping
  44956. events[index].isDone = false;
  44957. }
  44958. }
  44959. if (!returnValue) {
  44960. this._stopped = true;
  44961. }
  44962. return returnValue;
  44963. };
  44964. return RuntimeAnimation;
  44965. }());
  44966. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44967. })(BABYLON || (BABYLON = {}));
  44968. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44969. var BABYLON;
  44970. (function (BABYLON) {
  44971. var Animatable = /** @class */ (function () {
  44972. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44973. if (fromFrame === void 0) { fromFrame = 0; }
  44974. if (toFrame === void 0) { toFrame = 100; }
  44975. if (loopAnimation === void 0) { loopAnimation = false; }
  44976. if (speedRatio === void 0) { speedRatio = 1.0; }
  44977. this.target = target;
  44978. this.fromFrame = fromFrame;
  44979. this.toFrame = toFrame;
  44980. this.loopAnimation = loopAnimation;
  44981. this.onAnimationEnd = onAnimationEnd;
  44982. this._localDelayOffset = null;
  44983. this._pausedDelay = null;
  44984. this._runtimeAnimations = new Array();
  44985. this._paused = false;
  44986. this._speedRatio = 1;
  44987. this.animationStarted = false;
  44988. if (animations) {
  44989. this.appendAnimations(target, animations);
  44990. }
  44991. this._speedRatio = speedRatio;
  44992. this._scene = scene;
  44993. scene._activeAnimatables.push(this);
  44994. }
  44995. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44996. get: function () {
  44997. return this._speedRatio;
  44998. },
  44999. set: function (value) {
  45000. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  45001. var animation = this._runtimeAnimations[index];
  45002. animation._prepareForSpeedRatioChange(value);
  45003. }
  45004. this._speedRatio = value;
  45005. },
  45006. enumerable: true,
  45007. configurable: true
  45008. });
  45009. // Methods
  45010. Animatable.prototype.getAnimations = function () {
  45011. return this._runtimeAnimations;
  45012. };
  45013. Animatable.prototype.appendAnimations = function (target, animations) {
  45014. for (var index = 0; index < animations.length; index++) {
  45015. var animation = animations[index];
  45016. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  45017. }
  45018. };
  45019. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  45020. var runtimeAnimations = this._runtimeAnimations;
  45021. for (var index = 0; index < runtimeAnimations.length; index++) {
  45022. if (runtimeAnimations[index].animation.targetProperty === property) {
  45023. return runtimeAnimations[index].animation;
  45024. }
  45025. }
  45026. return null;
  45027. };
  45028. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  45029. var runtimeAnimations = this._runtimeAnimations;
  45030. for (var index = 0; index < runtimeAnimations.length; index++) {
  45031. if (runtimeAnimations[index].animation.targetProperty === property) {
  45032. return runtimeAnimations[index];
  45033. }
  45034. }
  45035. return null;
  45036. };
  45037. Animatable.prototype.reset = function () {
  45038. var runtimeAnimations = this._runtimeAnimations;
  45039. for (var index = 0; index < runtimeAnimations.length; index++) {
  45040. runtimeAnimations[index].reset();
  45041. }
  45042. // Reset to original value
  45043. for (index = 0; index < runtimeAnimations.length; index++) {
  45044. var animation = runtimeAnimations[index];
  45045. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  45046. }
  45047. this._localDelayOffset = null;
  45048. this._pausedDelay = null;
  45049. };
  45050. Animatable.prototype.enableBlending = function (blendingSpeed) {
  45051. var runtimeAnimations = this._runtimeAnimations;
  45052. for (var index = 0; index < runtimeAnimations.length; index++) {
  45053. runtimeAnimations[index].animation.enableBlending = true;
  45054. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  45055. }
  45056. };
  45057. Animatable.prototype.disableBlending = function () {
  45058. var runtimeAnimations = this._runtimeAnimations;
  45059. for (var index = 0; index < runtimeAnimations.length; index++) {
  45060. runtimeAnimations[index].animation.enableBlending = false;
  45061. }
  45062. };
  45063. Animatable.prototype.goToFrame = function (frame) {
  45064. var runtimeAnimations = this._runtimeAnimations;
  45065. if (runtimeAnimations[0]) {
  45066. var fps = runtimeAnimations[0].animation.framePerSecond;
  45067. var currentFrame = runtimeAnimations[0].currentFrame;
  45068. var adjustTime = frame - currentFrame;
  45069. var delay = adjustTime * 1000 / fps;
  45070. if (this._localDelayOffset === null) {
  45071. this._localDelayOffset = 0;
  45072. }
  45073. this._localDelayOffset -= delay;
  45074. }
  45075. for (var index = 0; index < runtimeAnimations.length; index++) {
  45076. runtimeAnimations[index].goToFrame(frame);
  45077. }
  45078. };
  45079. Animatable.prototype.pause = function () {
  45080. if (this._paused) {
  45081. return;
  45082. }
  45083. this._paused = true;
  45084. };
  45085. Animatable.prototype.restart = function () {
  45086. this._paused = false;
  45087. };
  45088. Animatable.prototype.stop = function (animationName) {
  45089. if (animationName) {
  45090. var idx = this._scene._activeAnimatables.indexOf(this);
  45091. if (idx > -1) {
  45092. var runtimeAnimations = this._runtimeAnimations;
  45093. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  45094. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  45095. continue;
  45096. }
  45097. runtimeAnimations[index].dispose();
  45098. runtimeAnimations.splice(index, 1);
  45099. }
  45100. if (runtimeAnimations.length == 0) {
  45101. this._scene._activeAnimatables.splice(idx, 1);
  45102. if (this.onAnimationEnd) {
  45103. this.onAnimationEnd();
  45104. }
  45105. }
  45106. }
  45107. }
  45108. else {
  45109. var index = this._scene._activeAnimatables.indexOf(this);
  45110. if (index > -1) {
  45111. this._scene._activeAnimatables.splice(index, 1);
  45112. var runtimeAnimations = this._runtimeAnimations;
  45113. for (var index = 0; index < runtimeAnimations.length; index++) {
  45114. runtimeAnimations[index].dispose();
  45115. }
  45116. if (this.onAnimationEnd) {
  45117. this.onAnimationEnd();
  45118. }
  45119. }
  45120. }
  45121. };
  45122. Animatable.prototype._animate = function (delay) {
  45123. if (this._paused) {
  45124. this.animationStarted = false;
  45125. if (this._pausedDelay === null) {
  45126. this._pausedDelay = delay;
  45127. }
  45128. return true;
  45129. }
  45130. if (this._localDelayOffset === null) {
  45131. this._localDelayOffset = delay;
  45132. this._pausedDelay = null;
  45133. }
  45134. else if (this._pausedDelay !== null) {
  45135. this._localDelayOffset += delay - this._pausedDelay;
  45136. this._pausedDelay = null;
  45137. }
  45138. // Animating
  45139. var running = false;
  45140. var runtimeAnimations = this._runtimeAnimations;
  45141. var index;
  45142. for (index = 0; index < runtimeAnimations.length; index++) {
  45143. var animation = runtimeAnimations[index];
  45144. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  45145. running = running || isRunning;
  45146. }
  45147. this.animationStarted = running;
  45148. if (!running) {
  45149. // Remove from active animatables
  45150. index = this._scene._activeAnimatables.indexOf(this);
  45151. this._scene._activeAnimatables.splice(index, 1);
  45152. // Dispose all runtime animations
  45153. for (index = 0; index < runtimeAnimations.length; index++) {
  45154. runtimeAnimations[index].dispose();
  45155. }
  45156. }
  45157. if (!running && this.onAnimationEnd) {
  45158. this.onAnimationEnd();
  45159. this.onAnimationEnd = null;
  45160. }
  45161. return running;
  45162. };
  45163. return Animatable;
  45164. }());
  45165. BABYLON.Animatable = Animatable;
  45166. })(BABYLON || (BABYLON = {}));
  45167. //# sourceMappingURL=babylon.animatable.js.map
  45168. var BABYLON;
  45169. (function (BABYLON) {
  45170. var EasingFunction = /** @class */ (function () {
  45171. function EasingFunction() {
  45172. // Properties
  45173. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  45174. }
  45175. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  45176. get: function () {
  45177. return EasingFunction._EASINGMODE_EASEIN;
  45178. },
  45179. enumerable: true,
  45180. configurable: true
  45181. });
  45182. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  45183. get: function () {
  45184. return EasingFunction._EASINGMODE_EASEOUT;
  45185. },
  45186. enumerable: true,
  45187. configurable: true
  45188. });
  45189. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  45190. get: function () {
  45191. return EasingFunction._EASINGMODE_EASEINOUT;
  45192. },
  45193. enumerable: true,
  45194. configurable: true
  45195. });
  45196. EasingFunction.prototype.setEasingMode = function (easingMode) {
  45197. var n = Math.min(Math.max(easingMode, 0), 2);
  45198. this._easingMode = n;
  45199. };
  45200. EasingFunction.prototype.getEasingMode = function () {
  45201. return this._easingMode;
  45202. };
  45203. EasingFunction.prototype.easeInCore = function (gradient) {
  45204. throw new Error('You must implement this method');
  45205. };
  45206. EasingFunction.prototype.ease = function (gradient) {
  45207. switch (this._easingMode) {
  45208. case EasingFunction.EASINGMODE_EASEIN:
  45209. return this.easeInCore(gradient);
  45210. case EasingFunction.EASINGMODE_EASEOUT:
  45211. return (1 - this.easeInCore(1 - gradient));
  45212. }
  45213. if (gradient >= 0.5) {
  45214. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  45215. }
  45216. return (this.easeInCore(gradient * 2) * 0.5);
  45217. };
  45218. //Statics
  45219. EasingFunction._EASINGMODE_EASEIN = 0;
  45220. EasingFunction._EASINGMODE_EASEOUT = 1;
  45221. EasingFunction._EASINGMODE_EASEINOUT = 2;
  45222. return EasingFunction;
  45223. }());
  45224. BABYLON.EasingFunction = EasingFunction;
  45225. var CircleEase = /** @class */ (function (_super) {
  45226. __extends(CircleEase, _super);
  45227. function CircleEase() {
  45228. return _super !== null && _super.apply(this, arguments) || this;
  45229. }
  45230. CircleEase.prototype.easeInCore = function (gradient) {
  45231. gradient = Math.max(0, Math.min(1, gradient));
  45232. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  45233. };
  45234. return CircleEase;
  45235. }(EasingFunction));
  45236. BABYLON.CircleEase = CircleEase;
  45237. var BackEase = /** @class */ (function (_super) {
  45238. __extends(BackEase, _super);
  45239. function BackEase(amplitude) {
  45240. if (amplitude === void 0) { amplitude = 1; }
  45241. var _this = _super.call(this) || this;
  45242. _this.amplitude = amplitude;
  45243. return _this;
  45244. }
  45245. BackEase.prototype.easeInCore = function (gradient) {
  45246. var num = Math.max(0, this.amplitude);
  45247. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  45248. };
  45249. return BackEase;
  45250. }(EasingFunction));
  45251. BABYLON.BackEase = BackEase;
  45252. var BounceEase = /** @class */ (function (_super) {
  45253. __extends(BounceEase, _super);
  45254. function BounceEase(bounces, bounciness) {
  45255. if (bounces === void 0) { bounces = 3; }
  45256. if (bounciness === void 0) { bounciness = 2; }
  45257. var _this = _super.call(this) || this;
  45258. _this.bounces = bounces;
  45259. _this.bounciness = bounciness;
  45260. return _this;
  45261. }
  45262. BounceEase.prototype.easeInCore = function (gradient) {
  45263. var y = Math.max(0.0, this.bounces);
  45264. var bounciness = this.bounciness;
  45265. if (bounciness <= 1.0) {
  45266. bounciness = 1.001;
  45267. }
  45268. var num9 = Math.pow(bounciness, y);
  45269. var num5 = 1.0 - bounciness;
  45270. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  45271. var num15 = gradient * num4;
  45272. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  45273. var num3 = Math.floor(num65);
  45274. var num13 = num3 + 1.0;
  45275. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  45276. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  45277. var num7 = (num8 + num12) * 0.5;
  45278. var num6 = gradient - num7;
  45279. var num2 = num7 - num8;
  45280. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  45281. };
  45282. return BounceEase;
  45283. }(EasingFunction));
  45284. BABYLON.BounceEase = BounceEase;
  45285. var CubicEase = /** @class */ (function (_super) {
  45286. __extends(CubicEase, _super);
  45287. function CubicEase() {
  45288. return _super !== null && _super.apply(this, arguments) || this;
  45289. }
  45290. CubicEase.prototype.easeInCore = function (gradient) {
  45291. return (gradient * gradient * gradient);
  45292. };
  45293. return CubicEase;
  45294. }(EasingFunction));
  45295. BABYLON.CubicEase = CubicEase;
  45296. var ElasticEase = /** @class */ (function (_super) {
  45297. __extends(ElasticEase, _super);
  45298. function ElasticEase(oscillations, springiness) {
  45299. if (oscillations === void 0) { oscillations = 3; }
  45300. if (springiness === void 0) { springiness = 3; }
  45301. var _this = _super.call(this) || this;
  45302. _this.oscillations = oscillations;
  45303. _this.springiness = springiness;
  45304. return _this;
  45305. }
  45306. ElasticEase.prototype.easeInCore = function (gradient) {
  45307. var num2;
  45308. var num3 = Math.max(0.0, this.oscillations);
  45309. var num = Math.max(0.0, this.springiness);
  45310. if (num == 0) {
  45311. num2 = gradient;
  45312. }
  45313. else {
  45314. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  45315. }
  45316. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  45317. };
  45318. return ElasticEase;
  45319. }(EasingFunction));
  45320. BABYLON.ElasticEase = ElasticEase;
  45321. var ExponentialEase = /** @class */ (function (_super) {
  45322. __extends(ExponentialEase, _super);
  45323. function ExponentialEase(exponent) {
  45324. if (exponent === void 0) { exponent = 2; }
  45325. var _this = _super.call(this) || this;
  45326. _this.exponent = exponent;
  45327. return _this;
  45328. }
  45329. ExponentialEase.prototype.easeInCore = function (gradient) {
  45330. if (this.exponent <= 0) {
  45331. return gradient;
  45332. }
  45333. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  45334. };
  45335. return ExponentialEase;
  45336. }(EasingFunction));
  45337. BABYLON.ExponentialEase = ExponentialEase;
  45338. var PowerEase = /** @class */ (function (_super) {
  45339. __extends(PowerEase, _super);
  45340. function PowerEase(power) {
  45341. if (power === void 0) { power = 2; }
  45342. var _this = _super.call(this) || this;
  45343. _this.power = power;
  45344. return _this;
  45345. }
  45346. PowerEase.prototype.easeInCore = function (gradient) {
  45347. var y = Math.max(0.0, this.power);
  45348. return Math.pow(gradient, y);
  45349. };
  45350. return PowerEase;
  45351. }(EasingFunction));
  45352. BABYLON.PowerEase = PowerEase;
  45353. var QuadraticEase = /** @class */ (function (_super) {
  45354. __extends(QuadraticEase, _super);
  45355. function QuadraticEase() {
  45356. return _super !== null && _super.apply(this, arguments) || this;
  45357. }
  45358. QuadraticEase.prototype.easeInCore = function (gradient) {
  45359. return (gradient * gradient);
  45360. };
  45361. return QuadraticEase;
  45362. }(EasingFunction));
  45363. BABYLON.QuadraticEase = QuadraticEase;
  45364. var QuarticEase = /** @class */ (function (_super) {
  45365. __extends(QuarticEase, _super);
  45366. function QuarticEase() {
  45367. return _super !== null && _super.apply(this, arguments) || this;
  45368. }
  45369. QuarticEase.prototype.easeInCore = function (gradient) {
  45370. return (gradient * gradient * gradient * gradient);
  45371. };
  45372. return QuarticEase;
  45373. }(EasingFunction));
  45374. BABYLON.QuarticEase = QuarticEase;
  45375. var QuinticEase = /** @class */ (function (_super) {
  45376. __extends(QuinticEase, _super);
  45377. function QuinticEase() {
  45378. return _super !== null && _super.apply(this, arguments) || this;
  45379. }
  45380. QuinticEase.prototype.easeInCore = function (gradient) {
  45381. return (gradient * gradient * gradient * gradient * gradient);
  45382. };
  45383. return QuinticEase;
  45384. }(EasingFunction));
  45385. BABYLON.QuinticEase = QuinticEase;
  45386. var SineEase = /** @class */ (function (_super) {
  45387. __extends(SineEase, _super);
  45388. function SineEase() {
  45389. return _super !== null && _super.apply(this, arguments) || this;
  45390. }
  45391. SineEase.prototype.easeInCore = function (gradient) {
  45392. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  45393. };
  45394. return SineEase;
  45395. }(EasingFunction));
  45396. BABYLON.SineEase = SineEase;
  45397. var BezierCurveEase = /** @class */ (function (_super) {
  45398. __extends(BezierCurveEase, _super);
  45399. function BezierCurveEase(x1, y1, x2, y2) {
  45400. if (x1 === void 0) { x1 = 0; }
  45401. if (y1 === void 0) { y1 = 0; }
  45402. if (x2 === void 0) { x2 = 1; }
  45403. if (y2 === void 0) { y2 = 1; }
  45404. var _this = _super.call(this) || this;
  45405. _this.x1 = x1;
  45406. _this.y1 = y1;
  45407. _this.x2 = x2;
  45408. _this.y2 = y2;
  45409. return _this;
  45410. }
  45411. BezierCurveEase.prototype.easeInCore = function (gradient) {
  45412. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  45413. };
  45414. return BezierCurveEase;
  45415. }(EasingFunction));
  45416. BABYLON.BezierCurveEase = BezierCurveEase;
  45417. })(BABYLON || (BABYLON = {}));
  45418. //# sourceMappingURL=babylon.easing.js.map
  45419. var BABYLON;
  45420. (function (BABYLON) {
  45421. var Condition = /** @class */ (function () {
  45422. function Condition(actionManager) {
  45423. this._actionManager = actionManager;
  45424. }
  45425. Condition.prototype.isValid = function () {
  45426. return true;
  45427. };
  45428. Condition.prototype._getProperty = function (propertyPath) {
  45429. return this._actionManager._getProperty(propertyPath);
  45430. };
  45431. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  45432. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45433. };
  45434. Condition.prototype.serialize = function () {
  45435. };
  45436. Condition.prototype._serialize = function (serializedCondition) {
  45437. return {
  45438. type: 2,
  45439. children: [],
  45440. name: serializedCondition.name,
  45441. properties: serializedCondition.properties
  45442. };
  45443. };
  45444. return Condition;
  45445. }());
  45446. BABYLON.Condition = Condition;
  45447. var ValueCondition = /** @class */ (function (_super) {
  45448. __extends(ValueCondition, _super);
  45449. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  45450. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  45451. var _this = _super.call(this, actionManager) || this;
  45452. _this.propertyPath = propertyPath;
  45453. _this.value = value;
  45454. _this.operator = operator;
  45455. _this._target = target;
  45456. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  45457. _this._property = _this._getProperty(_this.propertyPath);
  45458. return _this;
  45459. }
  45460. Object.defineProperty(ValueCondition, "IsEqual", {
  45461. get: function () {
  45462. return ValueCondition._IsEqual;
  45463. },
  45464. enumerable: true,
  45465. configurable: true
  45466. });
  45467. Object.defineProperty(ValueCondition, "IsDifferent", {
  45468. get: function () {
  45469. return ValueCondition._IsDifferent;
  45470. },
  45471. enumerable: true,
  45472. configurable: true
  45473. });
  45474. Object.defineProperty(ValueCondition, "IsGreater", {
  45475. get: function () {
  45476. return ValueCondition._IsGreater;
  45477. },
  45478. enumerable: true,
  45479. configurable: true
  45480. });
  45481. Object.defineProperty(ValueCondition, "IsLesser", {
  45482. get: function () {
  45483. return ValueCondition._IsLesser;
  45484. },
  45485. enumerable: true,
  45486. configurable: true
  45487. });
  45488. // Methods
  45489. ValueCondition.prototype.isValid = function () {
  45490. switch (this.operator) {
  45491. case ValueCondition.IsGreater:
  45492. return this._effectiveTarget[this._property] > this.value;
  45493. case ValueCondition.IsLesser:
  45494. return this._effectiveTarget[this._property] < this.value;
  45495. case ValueCondition.IsEqual:
  45496. case ValueCondition.IsDifferent:
  45497. var check;
  45498. if (this.value.equals) {
  45499. check = this.value.equals(this._effectiveTarget[this._property]);
  45500. }
  45501. else {
  45502. check = this.value === this._effectiveTarget[this._property];
  45503. }
  45504. return this.operator === ValueCondition.IsEqual ? check : !check;
  45505. }
  45506. return false;
  45507. };
  45508. ValueCondition.prototype.serialize = function () {
  45509. return this._serialize({
  45510. name: "ValueCondition",
  45511. properties: [
  45512. BABYLON.Action._GetTargetProperty(this._target),
  45513. { name: "propertyPath", value: this.propertyPath },
  45514. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45515. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  45516. ]
  45517. });
  45518. };
  45519. ValueCondition.GetOperatorName = function (operator) {
  45520. switch (operator) {
  45521. case ValueCondition._IsEqual: return "IsEqual";
  45522. case ValueCondition._IsDifferent: return "IsDifferent";
  45523. case ValueCondition._IsGreater: return "IsGreater";
  45524. case ValueCondition._IsLesser: return "IsLesser";
  45525. default: return "";
  45526. }
  45527. };
  45528. // Statics
  45529. ValueCondition._IsEqual = 0;
  45530. ValueCondition._IsDifferent = 1;
  45531. ValueCondition._IsGreater = 2;
  45532. ValueCondition._IsLesser = 3;
  45533. return ValueCondition;
  45534. }(Condition));
  45535. BABYLON.ValueCondition = ValueCondition;
  45536. var PredicateCondition = /** @class */ (function (_super) {
  45537. __extends(PredicateCondition, _super);
  45538. function PredicateCondition(actionManager, predicate) {
  45539. var _this = _super.call(this, actionManager) || this;
  45540. _this.predicate = predicate;
  45541. return _this;
  45542. }
  45543. PredicateCondition.prototype.isValid = function () {
  45544. return this.predicate();
  45545. };
  45546. return PredicateCondition;
  45547. }(Condition));
  45548. BABYLON.PredicateCondition = PredicateCondition;
  45549. var StateCondition = /** @class */ (function (_super) {
  45550. __extends(StateCondition, _super);
  45551. function StateCondition(actionManager, target, value) {
  45552. var _this = _super.call(this, actionManager) || this;
  45553. _this.value = value;
  45554. _this._target = target;
  45555. return _this;
  45556. }
  45557. // Methods
  45558. StateCondition.prototype.isValid = function () {
  45559. return this._target.state === this.value;
  45560. };
  45561. StateCondition.prototype.serialize = function () {
  45562. return this._serialize({
  45563. name: "StateCondition",
  45564. properties: [
  45565. BABYLON.Action._GetTargetProperty(this._target),
  45566. { name: "value", value: this.value }
  45567. ]
  45568. });
  45569. };
  45570. return StateCondition;
  45571. }(Condition));
  45572. BABYLON.StateCondition = StateCondition;
  45573. })(BABYLON || (BABYLON = {}));
  45574. //# sourceMappingURL=babylon.condition.js.map
  45575. var BABYLON;
  45576. (function (BABYLON) {
  45577. var Action = /** @class */ (function () {
  45578. function Action(triggerOptions, condition) {
  45579. this.triggerOptions = triggerOptions;
  45580. this.onBeforeExecuteObservable = new BABYLON.Observable();
  45581. if (triggerOptions.parameter) {
  45582. this.trigger = triggerOptions.trigger;
  45583. this._triggerParameter = triggerOptions.parameter;
  45584. }
  45585. else {
  45586. this.trigger = triggerOptions;
  45587. }
  45588. this._nextActiveAction = this;
  45589. this._condition = condition;
  45590. }
  45591. // Methods
  45592. Action.prototype._prepare = function () {
  45593. };
  45594. Action.prototype.getTriggerParameter = function () {
  45595. return this._triggerParameter;
  45596. };
  45597. Action.prototype._executeCurrent = function (evt) {
  45598. if (this._nextActiveAction._condition) {
  45599. var condition = this._nextActiveAction._condition;
  45600. var currentRenderId = this._actionManager.getScene().getRenderId();
  45601. // We cache the current evaluation for the current frame
  45602. if (condition._evaluationId === currentRenderId) {
  45603. if (!condition._currentResult) {
  45604. return;
  45605. }
  45606. }
  45607. else {
  45608. condition._evaluationId = currentRenderId;
  45609. if (!condition.isValid()) {
  45610. condition._currentResult = false;
  45611. return;
  45612. }
  45613. condition._currentResult = true;
  45614. }
  45615. }
  45616. this.onBeforeExecuteObservable.notifyObservers(this);
  45617. this._nextActiveAction.execute(evt);
  45618. this.skipToNextActiveAction();
  45619. };
  45620. Action.prototype.execute = function (evt) {
  45621. };
  45622. Action.prototype.skipToNextActiveAction = function () {
  45623. if (this._nextActiveAction._child) {
  45624. if (!this._nextActiveAction._child._actionManager) {
  45625. this._nextActiveAction._child._actionManager = this._actionManager;
  45626. }
  45627. this._nextActiveAction = this._nextActiveAction._child;
  45628. }
  45629. else {
  45630. this._nextActiveAction = this;
  45631. }
  45632. };
  45633. Action.prototype.then = function (action) {
  45634. this._child = action;
  45635. action._actionManager = this._actionManager;
  45636. action._prepare();
  45637. return action;
  45638. };
  45639. Action.prototype._getProperty = function (propertyPath) {
  45640. return this._actionManager._getProperty(propertyPath);
  45641. };
  45642. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45643. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45644. };
  45645. Action.prototype.serialize = function (parent) {
  45646. };
  45647. // Called by BABYLON.Action objects in serialize(...). Internal use
  45648. Action.prototype._serialize = function (serializedAction, parent) {
  45649. var serializationObject = {
  45650. type: 1,
  45651. children: [],
  45652. name: serializedAction.name,
  45653. properties: serializedAction.properties || []
  45654. };
  45655. // Serialize child
  45656. if (this._child) {
  45657. this._child.serialize(serializationObject);
  45658. }
  45659. // Check if "this" has a condition
  45660. if (this._condition) {
  45661. var serializedCondition = this._condition.serialize();
  45662. serializedCondition.children.push(serializationObject);
  45663. if (parent) {
  45664. parent.children.push(serializedCondition);
  45665. }
  45666. return serializedCondition;
  45667. }
  45668. if (parent) {
  45669. parent.children.push(serializationObject);
  45670. }
  45671. return serializationObject;
  45672. };
  45673. Action._SerializeValueAsString = function (value) {
  45674. if (typeof value === "number") {
  45675. return value.toString();
  45676. }
  45677. if (typeof value === "boolean") {
  45678. return value ? "true" : "false";
  45679. }
  45680. if (value instanceof BABYLON.Vector2) {
  45681. return value.x + ", " + value.y;
  45682. }
  45683. if (value instanceof BABYLON.Vector3) {
  45684. return value.x + ", " + value.y + ", " + value.z;
  45685. }
  45686. if (value instanceof BABYLON.Color3) {
  45687. return value.r + ", " + value.g + ", " + value.b;
  45688. }
  45689. if (value instanceof BABYLON.Color4) {
  45690. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45691. }
  45692. return value; // string
  45693. };
  45694. Action._GetTargetProperty = function (target) {
  45695. return {
  45696. name: "target",
  45697. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45698. : target instanceof BABYLON.Light ? "LightProperties"
  45699. : target instanceof BABYLON.Camera ? "CameraProperties"
  45700. : "SceneProperties",
  45701. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45702. };
  45703. };
  45704. return Action;
  45705. }());
  45706. BABYLON.Action = Action;
  45707. })(BABYLON || (BABYLON = {}));
  45708. //# sourceMappingURL=babylon.action.js.map
  45709. var BABYLON;
  45710. (function (BABYLON) {
  45711. /**
  45712. * ActionEvent is the event beint sent when an action is triggered.
  45713. */
  45714. var ActionEvent = /** @class */ (function () {
  45715. /**
  45716. * @param source The mesh or sprite that triggered the action.
  45717. * @param pointerX The X mouse cursor position at the time of the event
  45718. * @param pointerY The Y mouse cursor position at the time of the event
  45719. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45720. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45721. */
  45722. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45723. this.source = source;
  45724. this.pointerX = pointerX;
  45725. this.pointerY = pointerY;
  45726. this.meshUnderPointer = meshUnderPointer;
  45727. this.sourceEvent = sourceEvent;
  45728. this.additionalData = additionalData;
  45729. }
  45730. /**
  45731. * Helper function to auto-create an ActionEvent from a source mesh.
  45732. * @param source The source mesh that triggered the event
  45733. * @param evt {Event} The original (browser) event
  45734. */
  45735. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45736. var scene = source.getScene();
  45737. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45738. };
  45739. /**
  45740. * Helper function to auto-create an ActionEvent from a source mesh.
  45741. * @param source The source sprite that triggered the event
  45742. * @param scene Scene associated with the sprite
  45743. * @param evt {Event} The original (browser) event
  45744. */
  45745. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45746. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45747. };
  45748. /**
  45749. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45750. * @param scene the scene where the event occurred
  45751. * @param evt {Event} The original (browser) event
  45752. */
  45753. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45754. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45755. };
  45756. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45757. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45758. };
  45759. return ActionEvent;
  45760. }());
  45761. BABYLON.ActionEvent = ActionEvent;
  45762. /**
  45763. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45764. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45765. */
  45766. var ActionManager = /** @class */ (function () {
  45767. function ActionManager(scene) {
  45768. // Members
  45769. this.actions = new Array();
  45770. this.hoverCursor = '';
  45771. this._scene = scene;
  45772. scene._actionManagers.push(this);
  45773. }
  45774. Object.defineProperty(ActionManager, "NothingTrigger", {
  45775. get: function () {
  45776. return ActionManager._NothingTrigger;
  45777. },
  45778. enumerable: true,
  45779. configurable: true
  45780. });
  45781. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45782. get: function () {
  45783. return ActionManager._OnPickTrigger;
  45784. },
  45785. enumerable: true,
  45786. configurable: true
  45787. });
  45788. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  45789. get: function () {
  45790. return ActionManager._OnLeftPickTrigger;
  45791. },
  45792. enumerable: true,
  45793. configurable: true
  45794. });
  45795. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  45796. get: function () {
  45797. return ActionManager._OnRightPickTrigger;
  45798. },
  45799. enumerable: true,
  45800. configurable: true
  45801. });
  45802. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  45803. get: function () {
  45804. return ActionManager._OnCenterPickTrigger;
  45805. },
  45806. enumerable: true,
  45807. configurable: true
  45808. });
  45809. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  45810. get: function () {
  45811. return ActionManager._OnPickDownTrigger;
  45812. },
  45813. enumerable: true,
  45814. configurable: true
  45815. });
  45816. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  45817. get: function () {
  45818. return ActionManager._OnDoublePickTrigger;
  45819. },
  45820. enumerable: true,
  45821. configurable: true
  45822. });
  45823. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  45824. get: function () {
  45825. return ActionManager._OnPickUpTrigger;
  45826. },
  45827. enumerable: true,
  45828. configurable: true
  45829. });
  45830. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  45831. /// This trigger will only be raised if you also declared a OnPickDown
  45832. get: function () {
  45833. return ActionManager._OnPickOutTrigger;
  45834. },
  45835. enumerable: true,
  45836. configurable: true
  45837. });
  45838. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  45839. get: function () {
  45840. return ActionManager._OnLongPressTrigger;
  45841. },
  45842. enumerable: true,
  45843. configurable: true
  45844. });
  45845. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  45846. get: function () {
  45847. return ActionManager._OnPointerOverTrigger;
  45848. },
  45849. enumerable: true,
  45850. configurable: true
  45851. });
  45852. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  45853. get: function () {
  45854. return ActionManager._OnPointerOutTrigger;
  45855. },
  45856. enumerable: true,
  45857. configurable: true
  45858. });
  45859. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  45860. get: function () {
  45861. return ActionManager._OnEveryFrameTrigger;
  45862. },
  45863. enumerable: true,
  45864. configurable: true
  45865. });
  45866. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  45867. get: function () {
  45868. return ActionManager._OnIntersectionEnterTrigger;
  45869. },
  45870. enumerable: true,
  45871. configurable: true
  45872. });
  45873. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  45874. get: function () {
  45875. return ActionManager._OnIntersectionExitTrigger;
  45876. },
  45877. enumerable: true,
  45878. configurable: true
  45879. });
  45880. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  45881. get: function () {
  45882. return ActionManager._OnKeyDownTrigger;
  45883. },
  45884. enumerable: true,
  45885. configurable: true
  45886. });
  45887. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45888. get: function () {
  45889. return ActionManager._OnKeyUpTrigger;
  45890. },
  45891. enumerable: true,
  45892. configurable: true
  45893. });
  45894. // Methods
  45895. ActionManager.prototype.dispose = function () {
  45896. var index = this._scene._actionManagers.indexOf(this);
  45897. for (var i = 0; i < this.actions.length; i++) {
  45898. var action = this.actions[i];
  45899. ActionManager.Triggers[action.trigger]--;
  45900. if (ActionManager.Triggers[action.trigger] === 0) {
  45901. delete ActionManager.Triggers[action.trigger];
  45902. }
  45903. }
  45904. if (index > -1) {
  45905. this._scene._actionManagers.splice(index, 1);
  45906. }
  45907. };
  45908. ActionManager.prototype.getScene = function () {
  45909. return this._scene;
  45910. };
  45911. /**
  45912. * Does this action manager handles actions of any of the given triggers
  45913. * @param {number[]} triggers - the triggers to be tested
  45914. * @return {boolean} whether one (or more) of the triggers is handeled
  45915. */
  45916. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45917. for (var index = 0; index < this.actions.length; index++) {
  45918. var action = this.actions[index];
  45919. if (triggers.indexOf(action.trigger) > -1) {
  45920. return true;
  45921. }
  45922. }
  45923. return false;
  45924. };
  45925. /**
  45926. * Does this action manager handles actions of a given trigger
  45927. * @param {number} trigger - the trigger to be tested
  45928. * @return {boolean} whether the trigger is handeled
  45929. */
  45930. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45931. for (var index = 0; index < this.actions.length; index++) {
  45932. var action = this.actions[index];
  45933. if (action.trigger === trigger) {
  45934. return true;
  45935. }
  45936. }
  45937. return false;
  45938. };
  45939. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45940. /**
  45941. * Does this action manager has pointer triggers
  45942. * @return {boolean} whether or not it has pointer triggers
  45943. */
  45944. get: function () {
  45945. for (var index = 0; index < this.actions.length; index++) {
  45946. var action = this.actions[index];
  45947. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45948. return true;
  45949. }
  45950. }
  45951. return false;
  45952. },
  45953. enumerable: true,
  45954. configurable: true
  45955. });
  45956. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45957. /**
  45958. * Does this action manager has pick triggers
  45959. * @return {boolean} whether or not it has pick triggers
  45960. */
  45961. get: function () {
  45962. for (var index = 0; index < this.actions.length; index++) {
  45963. var action = this.actions[index];
  45964. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45965. return true;
  45966. }
  45967. }
  45968. return false;
  45969. },
  45970. enumerable: true,
  45971. configurable: true
  45972. });
  45973. Object.defineProperty(ActionManager, "HasTriggers", {
  45974. /**
  45975. * Does exist one action manager with at least one trigger
  45976. * @return {boolean} whether or not it exists one action manager with one trigger
  45977. **/
  45978. get: function () {
  45979. for (var t in ActionManager.Triggers) {
  45980. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45981. return true;
  45982. }
  45983. }
  45984. return false;
  45985. },
  45986. enumerable: true,
  45987. configurable: true
  45988. });
  45989. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45990. /**
  45991. * Does exist one action manager with at least one pick trigger
  45992. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45993. **/
  45994. get: function () {
  45995. for (var t in ActionManager.Triggers) {
  45996. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45997. var t_int = parseInt(t);
  45998. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45999. return true;
  46000. }
  46001. }
  46002. }
  46003. return false;
  46004. },
  46005. enumerable: true,
  46006. configurable: true
  46007. });
  46008. /**
  46009. * Does exist one action manager that handles actions of a given trigger
  46010. * @param {number} trigger - the trigger to be tested
  46011. * @return {boolean} whether the trigger is handeled by at least one action manager
  46012. **/
  46013. ActionManager.HasSpecificTrigger = function (trigger) {
  46014. for (var t in ActionManager.Triggers) {
  46015. if (ActionManager.Triggers.hasOwnProperty(t)) {
  46016. var t_int = parseInt(t);
  46017. if (t_int === trigger) {
  46018. return true;
  46019. }
  46020. }
  46021. }
  46022. return false;
  46023. };
  46024. /**
  46025. * Registers an action to this action manager
  46026. * @param {BABYLON.Action} action - the action to be registered
  46027. * @return {BABYLON.Action} the action amended (prepared) after registration
  46028. */
  46029. ActionManager.prototype.registerAction = function (action) {
  46030. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  46031. if (this.getScene().actionManager !== this) {
  46032. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  46033. return null;
  46034. }
  46035. }
  46036. this.actions.push(action);
  46037. if (ActionManager.Triggers[action.trigger]) {
  46038. ActionManager.Triggers[action.trigger]++;
  46039. }
  46040. else {
  46041. ActionManager.Triggers[action.trigger] = 1;
  46042. }
  46043. action._actionManager = this;
  46044. action._prepare();
  46045. return action;
  46046. };
  46047. /**
  46048. * Unregisters an action to this action manager
  46049. * @param action The action to be unregistered
  46050. * @return whether the action has been unregistered
  46051. */
  46052. ActionManager.prototype.unregisterAction = function (action) {
  46053. var index = this.actions.indexOf(action);
  46054. if (index !== -1) {
  46055. this.actions.splice(index, 1);
  46056. ActionManager.Triggers[action.trigger] -= 1;
  46057. if (ActionManager.Triggers[action.trigger] === 0) {
  46058. delete ActionManager.Triggers[action.trigger];
  46059. }
  46060. delete action._actionManager;
  46061. return true;
  46062. }
  46063. return false;
  46064. };
  46065. /**
  46066. * Process a specific trigger
  46067. * @param {number} trigger - the trigger to process
  46068. * @param evt {BABYLON.ActionEvent} the event details to be processed
  46069. */
  46070. ActionManager.prototype.processTrigger = function (trigger, evt) {
  46071. for (var index = 0; index < this.actions.length; index++) {
  46072. var action = this.actions[index];
  46073. if (action.trigger === trigger) {
  46074. if (evt) {
  46075. if (trigger === ActionManager.OnKeyUpTrigger
  46076. || trigger === ActionManager.OnKeyDownTrigger) {
  46077. var parameter = action.getTriggerParameter();
  46078. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  46079. if (!parameter.toLowerCase) {
  46080. continue;
  46081. }
  46082. var lowerCase = parameter.toLowerCase();
  46083. if (lowerCase !== evt.sourceEvent.key) {
  46084. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  46085. var actualkey = String.fromCharCode(unicode).toLowerCase();
  46086. if (actualkey !== lowerCase) {
  46087. continue;
  46088. }
  46089. }
  46090. }
  46091. }
  46092. }
  46093. action._executeCurrent(evt);
  46094. }
  46095. }
  46096. };
  46097. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  46098. var properties = propertyPath.split(".");
  46099. for (var index = 0; index < properties.length - 1; index++) {
  46100. target = target[properties[index]];
  46101. }
  46102. return target;
  46103. };
  46104. ActionManager.prototype._getProperty = function (propertyPath) {
  46105. var properties = propertyPath.split(".");
  46106. return properties[properties.length - 1];
  46107. };
  46108. ActionManager.prototype.serialize = function (name) {
  46109. var root = {
  46110. children: new Array(),
  46111. name: name,
  46112. type: 3,
  46113. properties: new Array() // Empty for root but required
  46114. };
  46115. for (var i = 0; i < this.actions.length; i++) {
  46116. var triggerObject = {
  46117. type: 0,
  46118. children: new Array(),
  46119. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  46120. properties: new Array()
  46121. };
  46122. var triggerOptions = this.actions[i].triggerOptions;
  46123. if (triggerOptions && typeof triggerOptions !== "number") {
  46124. if (triggerOptions.parameter instanceof BABYLON.Node) {
  46125. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  46126. }
  46127. else {
  46128. var parameter = {};
  46129. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  46130. if (triggerOptions.parameter.mesh) {
  46131. parameter._meshId = triggerOptions.parameter.mesh.id;
  46132. }
  46133. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  46134. }
  46135. }
  46136. // Serialize child action, recursively
  46137. this.actions[i].serialize(triggerObject);
  46138. // Add serialized trigger
  46139. root.children.push(triggerObject);
  46140. }
  46141. return root;
  46142. };
  46143. ActionManager.Parse = function (parsedActions, object, scene) {
  46144. var actionManager = new ActionManager(scene);
  46145. if (object === null)
  46146. scene.actionManager = actionManager;
  46147. else
  46148. object.actionManager = actionManager;
  46149. // instanciate a new object
  46150. var instanciate = function (name, params) {
  46151. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  46152. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  46153. newInstance.constructor.apply(newInstance, params);
  46154. return newInstance;
  46155. };
  46156. var parseParameter = function (name, value, target, propertyPath) {
  46157. if (propertyPath === null) {
  46158. // String, boolean or float
  46159. var floatValue = parseFloat(value);
  46160. if (value === "true" || value === "false")
  46161. return value === "true";
  46162. else
  46163. return isNaN(floatValue) ? value : floatValue;
  46164. }
  46165. var effectiveTarget = propertyPath.split(".");
  46166. var values = value.split(",");
  46167. // Get effective Target
  46168. for (var i = 0; i < effectiveTarget.length; i++) {
  46169. target = target[effectiveTarget[i]];
  46170. }
  46171. // Return appropriate value with its type
  46172. if (typeof (target) === "boolean")
  46173. return values[0] === "true";
  46174. if (typeof (target) === "string")
  46175. return values[0];
  46176. // Parameters with multiple values such as Vector3 etc.
  46177. var split = new Array();
  46178. for (var i = 0; i < values.length; i++)
  46179. split.push(parseFloat(values[i]));
  46180. if (target instanceof BABYLON.Vector3)
  46181. return BABYLON.Vector3.FromArray(split);
  46182. if (target instanceof BABYLON.Vector4)
  46183. return BABYLON.Vector4.FromArray(split);
  46184. if (target instanceof BABYLON.Color3)
  46185. return BABYLON.Color3.FromArray(split);
  46186. if (target instanceof BABYLON.Color4)
  46187. return BABYLON.Color4.FromArray(split);
  46188. return parseFloat(values[0]);
  46189. };
  46190. // traverse graph per trigger
  46191. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  46192. if (combineArray === void 0) { combineArray = null; }
  46193. if (parsedAction.detached)
  46194. return;
  46195. var parameters = new Array();
  46196. var target = null;
  46197. var propertyPath = null;
  46198. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  46199. // Parameters
  46200. if (parsedAction.type === 2)
  46201. parameters.push(actionManager);
  46202. else
  46203. parameters.push(trigger);
  46204. if (combine) {
  46205. var actions = new Array();
  46206. for (var j = 0; j < parsedAction.combine.length; j++) {
  46207. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  46208. }
  46209. parameters.push(actions);
  46210. }
  46211. else {
  46212. for (var i = 0; i < parsedAction.properties.length; i++) {
  46213. var value = parsedAction.properties[i].value;
  46214. var name = parsedAction.properties[i].name;
  46215. var targetType = parsedAction.properties[i].targetType;
  46216. if (name === "target")
  46217. if (targetType !== null && targetType === "SceneProperties")
  46218. value = target = scene;
  46219. else
  46220. value = target = scene.getNodeByName(value);
  46221. else if (name === "parent")
  46222. value = scene.getNodeByName(value);
  46223. else if (name === "sound")
  46224. value = scene.getSoundByName(value);
  46225. else if (name !== "propertyPath") {
  46226. if (parsedAction.type === 2 && name === "operator")
  46227. value = BABYLON.ValueCondition[value];
  46228. else
  46229. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  46230. }
  46231. else {
  46232. propertyPath = value;
  46233. }
  46234. parameters.push(value);
  46235. }
  46236. }
  46237. if (combineArray === null) {
  46238. parameters.push(condition);
  46239. }
  46240. else {
  46241. parameters.push(null);
  46242. }
  46243. // If interpolate value action
  46244. if (parsedAction.name === "InterpolateValueAction") {
  46245. var param = parameters[parameters.length - 2];
  46246. parameters[parameters.length - 1] = param;
  46247. parameters[parameters.length - 2] = condition;
  46248. }
  46249. // Action or condition(s) and not CombineAction
  46250. var newAction = instanciate(parsedAction.name, parameters);
  46251. if (newAction instanceof BABYLON.Condition && condition !== null) {
  46252. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  46253. if (action)
  46254. action.then(nothing);
  46255. else
  46256. actionManager.registerAction(nothing);
  46257. action = nothing;
  46258. }
  46259. if (combineArray === null) {
  46260. if (newAction instanceof BABYLON.Condition) {
  46261. condition = newAction;
  46262. newAction = action;
  46263. }
  46264. else {
  46265. condition = null;
  46266. if (action)
  46267. action.then(newAction);
  46268. else
  46269. actionManager.registerAction(newAction);
  46270. }
  46271. }
  46272. else {
  46273. combineArray.push(newAction);
  46274. }
  46275. for (var i = 0; i < parsedAction.children.length; i++)
  46276. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  46277. };
  46278. // triggers
  46279. for (var i = 0; i < parsedActions.children.length; i++) {
  46280. var triggerParams;
  46281. var trigger = parsedActions.children[i];
  46282. if (trigger.properties.length > 0) {
  46283. var param = trigger.properties[0].value;
  46284. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  46285. if (value._meshId) {
  46286. value.mesh = scene.getMeshByID(value._meshId);
  46287. }
  46288. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  46289. }
  46290. else
  46291. triggerParams = ActionManager[trigger.name];
  46292. for (var j = 0; j < trigger.children.length; j++) {
  46293. if (!trigger.detached)
  46294. traverse(trigger.children[j], triggerParams, null, null);
  46295. }
  46296. }
  46297. };
  46298. ActionManager.GetTriggerName = function (trigger) {
  46299. switch (trigger) {
  46300. case 0: return "NothingTrigger";
  46301. case 1: return "OnPickTrigger";
  46302. case 2: return "OnLeftPickTrigger";
  46303. case 3: return "OnRightPickTrigger";
  46304. case 4: return "OnCenterPickTrigger";
  46305. case 5: return "OnPickDownTrigger";
  46306. case 6: return "OnPickUpTrigger";
  46307. case 7: return "OnLongPressTrigger";
  46308. case 8: return "OnPointerOverTrigger";
  46309. case 9: return "OnPointerOutTrigger";
  46310. case 10: return "OnEveryFrameTrigger";
  46311. case 11: return "OnIntersectionEnterTrigger";
  46312. case 12: return "OnIntersectionExitTrigger";
  46313. case 13: return "OnKeyDownTrigger";
  46314. case 14: return "OnKeyUpTrigger";
  46315. case 15: return "OnPickOutTrigger";
  46316. default: return "";
  46317. }
  46318. };
  46319. // Statics
  46320. ActionManager._NothingTrigger = 0;
  46321. ActionManager._OnPickTrigger = 1;
  46322. ActionManager._OnLeftPickTrigger = 2;
  46323. ActionManager._OnRightPickTrigger = 3;
  46324. ActionManager._OnCenterPickTrigger = 4;
  46325. ActionManager._OnPickDownTrigger = 5;
  46326. ActionManager._OnDoublePickTrigger = 6;
  46327. ActionManager._OnPickUpTrigger = 7;
  46328. ActionManager._OnLongPressTrigger = 8;
  46329. ActionManager._OnPointerOverTrigger = 9;
  46330. ActionManager._OnPointerOutTrigger = 10;
  46331. ActionManager._OnEveryFrameTrigger = 11;
  46332. ActionManager._OnIntersectionEnterTrigger = 12;
  46333. ActionManager._OnIntersectionExitTrigger = 13;
  46334. ActionManager._OnKeyDownTrigger = 14;
  46335. ActionManager._OnKeyUpTrigger = 15;
  46336. ActionManager._OnPickOutTrigger = 16;
  46337. ActionManager.Triggers = {};
  46338. return ActionManager;
  46339. }());
  46340. BABYLON.ActionManager = ActionManager;
  46341. })(BABYLON || (BABYLON = {}));
  46342. //# sourceMappingURL=babylon.actionManager.js.map
  46343. var BABYLON;
  46344. (function (BABYLON) {
  46345. var InterpolateValueAction = /** @class */ (function (_super) {
  46346. __extends(InterpolateValueAction, _super);
  46347. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  46348. if (duration === void 0) { duration = 1000; }
  46349. var _this = _super.call(this, triggerOptions, condition) || this;
  46350. _this.propertyPath = propertyPath;
  46351. _this.value = value;
  46352. _this.duration = duration;
  46353. _this.stopOtherAnimations = stopOtherAnimations;
  46354. _this.onInterpolationDone = onInterpolationDone;
  46355. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  46356. _this._target = _this._effectiveTarget = target;
  46357. return _this;
  46358. }
  46359. InterpolateValueAction.prototype._prepare = function () {
  46360. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46361. this._property = this._getProperty(this.propertyPath);
  46362. };
  46363. InterpolateValueAction.prototype.execute = function () {
  46364. var _this = this;
  46365. var scene = this._actionManager.getScene();
  46366. var keys = [
  46367. {
  46368. frame: 0,
  46369. value: this._effectiveTarget[this._property]
  46370. }, {
  46371. frame: 100,
  46372. value: this.value
  46373. }
  46374. ];
  46375. var dataType;
  46376. if (typeof this.value === "number") {
  46377. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  46378. }
  46379. else if (this.value instanceof BABYLON.Color3) {
  46380. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  46381. }
  46382. else if (this.value instanceof BABYLON.Vector3) {
  46383. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  46384. }
  46385. else if (this.value instanceof BABYLON.Matrix) {
  46386. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  46387. }
  46388. else if (this.value instanceof BABYLON.Quaternion) {
  46389. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  46390. }
  46391. else {
  46392. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  46393. return;
  46394. }
  46395. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  46396. animation.setKeys(keys);
  46397. if (this.stopOtherAnimations) {
  46398. scene.stopAnimation(this._effectiveTarget);
  46399. }
  46400. var wrapper = function () {
  46401. _this.onInterpolationDoneObservable.notifyObservers(_this);
  46402. if (_this.onInterpolationDone) {
  46403. _this.onInterpolationDone();
  46404. }
  46405. };
  46406. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  46407. };
  46408. InterpolateValueAction.prototype.serialize = function (parent) {
  46409. return _super.prototype._serialize.call(this, {
  46410. name: "InterpolateValueAction",
  46411. properties: [
  46412. BABYLON.Action._GetTargetProperty(this._target),
  46413. { name: "propertyPath", value: this.propertyPath },
  46414. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  46415. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  46416. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  46417. ]
  46418. }, parent);
  46419. };
  46420. return InterpolateValueAction;
  46421. }(BABYLON.Action));
  46422. BABYLON.InterpolateValueAction = InterpolateValueAction;
  46423. })(BABYLON || (BABYLON = {}));
  46424. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  46425. var BABYLON;
  46426. (function (BABYLON) {
  46427. var SwitchBooleanAction = /** @class */ (function (_super) {
  46428. __extends(SwitchBooleanAction, _super);
  46429. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  46430. var _this = _super.call(this, triggerOptions, condition) || this;
  46431. _this.propertyPath = propertyPath;
  46432. _this._target = _this._effectiveTarget = target;
  46433. return _this;
  46434. }
  46435. SwitchBooleanAction.prototype._prepare = function () {
  46436. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46437. this._property = this._getProperty(this.propertyPath);
  46438. };
  46439. SwitchBooleanAction.prototype.execute = function () {
  46440. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  46441. };
  46442. SwitchBooleanAction.prototype.serialize = function (parent) {
  46443. return _super.prototype._serialize.call(this, {
  46444. name: "SwitchBooleanAction",
  46445. properties: [
  46446. BABYLON.Action._GetTargetProperty(this._target),
  46447. { name: "propertyPath", value: this.propertyPath }
  46448. ]
  46449. }, parent);
  46450. };
  46451. return SwitchBooleanAction;
  46452. }(BABYLON.Action));
  46453. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  46454. var SetStateAction = /** @class */ (function (_super) {
  46455. __extends(SetStateAction, _super);
  46456. function SetStateAction(triggerOptions, target, value, condition) {
  46457. var _this = _super.call(this, triggerOptions, condition) || this;
  46458. _this.value = value;
  46459. _this._target = target;
  46460. return _this;
  46461. }
  46462. SetStateAction.prototype.execute = function () {
  46463. this._target.state = this.value;
  46464. };
  46465. SetStateAction.prototype.serialize = function (parent) {
  46466. return _super.prototype._serialize.call(this, {
  46467. name: "SetStateAction",
  46468. properties: [
  46469. BABYLON.Action._GetTargetProperty(this._target),
  46470. { name: "value", value: this.value }
  46471. ]
  46472. }, parent);
  46473. };
  46474. return SetStateAction;
  46475. }(BABYLON.Action));
  46476. BABYLON.SetStateAction = SetStateAction;
  46477. var SetValueAction = /** @class */ (function (_super) {
  46478. __extends(SetValueAction, _super);
  46479. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  46480. var _this = _super.call(this, triggerOptions, condition) || this;
  46481. _this.propertyPath = propertyPath;
  46482. _this.value = value;
  46483. _this._target = _this._effectiveTarget = target;
  46484. return _this;
  46485. }
  46486. SetValueAction.prototype._prepare = function () {
  46487. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46488. this._property = this._getProperty(this.propertyPath);
  46489. };
  46490. SetValueAction.prototype.execute = function () {
  46491. this._effectiveTarget[this._property] = this.value;
  46492. if (this._target.markAsDirty) {
  46493. this._target.markAsDirty(this._property);
  46494. }
  46495. };
  46496. SetValueAction.prototype.serialize = function (parent) {
  46497. return _super.prototype._serialize.call(this, {
  46498. name: "SetValueAction",
  46499. properties: [
  46500. BABYLON.Action._GetTargetProperty(this._target),
  46501. { name: "propertyPath", value: this.propertyPath },
  46502. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46503. ]
  46504. }, parent);
  46505. };
  46506. return SetValueAction;
  46507. }(BABYLON.Action));
  46508. BABYLON.SetValueAction = SetValueAction;
  46509. var IncrementValueAction = /** @class */ (function (_super) {
  46510. __extends(IncrementValueAction, _super);
  46511. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  46512. var _this = _super.call(this, triggerOptions, condition) || this;
  46513. _this.propertyPath = propertyPath;
  46514. _this.value = value;
  46515. _this._target = _this._effectiveTarget = target;
  46516. return _this;
  46517. }
  46518. IncrementValueAction.prototype._prepare = function () {
  46519. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  46520. this._property = this._getProperty(this.propertyPath);
  46521. if (typeof this._effectiveTarget[this._property] !== "number") {
  46522. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  46523. }
  46524. };
  46525. IncrementValueAction.prototype.execute = function () {
  46526. this._effectiveTarget[this._property] += this.value;
  46527. if (this._target.markAsDirty) {
  46528. this._target.markAsDirty(this._property);
  46529. }
  46530. };
  46531. IncrementValueAction.prototype.serialize = function (parent) {
  46532. return _super.prototype._serialize.call(this, {
  46533. name: "IncrementValueAction",
  46534. properties: [
  46535. BABYLON.Action._GetTargetProperty(this._target),
  46536. { name: "propertyPath", value: this.propertyPath },
  46537. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46538. ]
  46539. }, parent);
  46540. };
  46541. return IncrementValueAction;
  46542. }(BABYLON.Action));
  46543. BABYLON.IncrementValueAction = IncrementValueAction;
  46544. var PlayAnimationAction = /** @class */ (function (_super) {
  46545. __extends(PlayAnimationAction, _super);
  46546. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46547. var _this = _super.call(this, triggerOptions, condition) || this;
  46548. _this.from = from;
  46549. _this.to = to;
  46550. _this.loop = loop;
  46551. _this._target = target;
  46552. return _this;
  46553. }
  46554. PlayAnimationAction.prototype._prepare = function () {
  46555. };
  46556. PlayAnimationAction.prototype.execute = function () {
  46557. var scene = this._actionManager.getScene();
  46558. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46559. };
  46560. PlayAnimationAction.prototype.serialize = function (parent) {
  46561. return _super.prototype._serialize.call(this, {
  46562. name: "PlayAnimationAction",
  46563. properties: [
  46564. BABYLON.Action._GetTargetProperty(this._target),
  46565. { name: "from", value: String(this.from) },
  46566. { name: "to", value: String(this.to) },
  46567. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46568. ]
  46569. }, parent);
  46570. };
  46571. return PlayAnimationAction;
  46572. }(BABYLON.Action));
  46573. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46574. var StopAnimationAction = /** @class */ (function (_super) {
  46575. __extends(StopAnimationAction, _super);
  46576. function StopAnimationAction(triggerOptions, target, condition) {
  46577. var _this = _super.call(this, triggerOptions, condition) || this;
  46578. _this._target = target;
  46579. return _this;
  46580. }
  46581. StopAnimationAction.prototype._prepare = function () {
  46582. };
  46583. StopAnimationAction.prototype.execute = function () {
  46584. var scene = this._actionManager.getScene();
  46585. scene.stopAnimation(this._target);
  46586. };
  46587. StopAnimationAction.prototype.serialize = function (parent) {
  46588. return _super.prototype._serialize.call(this, {
  46589. name: "StopAnimationAction",
  46590. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46591. }, parent);
  46592. };
  46593. return StopAnimationAction;
  46594. }(BABYLON.Action));
  46595. BABYLON.StopAnimationAction = StopAnimationAction;
  46596. var DoNothingAction = /** @class */ (function (_super) {
  46597. __extends(DoNothingAction, _super);
  46598. function DoNothingAction(triggerOptions, condition) {
  46599. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46600. return _super.call(this, triggerOptions, condition) || this;
  46601. }
  46602. DoNothingAction.prototype.execute = function () {
  46603. };
  46604. DoNothingAction.prototype.serialize = function (parent) {
  46605. return _super.prototype._serialize.call(this, {
  46606. name: "DoNothingAction",
  46607. properties: []
  46608. }, parent);
  46609. };
  46610. return DoNothingAction;
  46611. }(BABYLON.Action));
  46612. BABYLON.DoNothingAction = DoNothingAction;
  46613. var CombineAction = /** @class */ (function (_super) {
  46614. __extends(CombineAction, _super);
  46615. function CombineAction(triggerOptions, children, condition) {
  46616. var _this = _super.call(this, triggerOptions, condition) || this;
  46617. _this.children = children;
  46618. return _this;
  46619. }
  46620. CombineAction.prototype._prepare = function () {
  46621. for (var index = 0; index < this.children.length; index++) {
  46622. this.children[index]._actionManager = this._actionManager;
  46623. this.children[index]._prepare();
  46624. }
  46625. };
  46626. CombineAction.prototype.execute = function (evt) {
  46627. for (var index = 0; index < this.children.length; index++) {
  46628. this.children[index].execute(evt);
  46629. }
  46630. };
  46631. CombineAction.prototype.serialize = function (parent) {
  46632. var serializationObject = _super.prototype._serialize.call(this, {
  46633. name: "CombineAction",
  46634. properties: [],
  46635. combine: []
  46636. }, parent);
  46637. for (var i = 0; i < this.children.length; i++) {
  46638. serializationObject.combine.push(this.children[i].serialize(null));
  46639. }
  46640. return serializationObject;
  46641. };
  46642. return CombineAction;
  46643. }(BABYLON.Action));
  46644. BABYLON.CombineAction = CombineAction;
  46645. var ExecuteCodeAction = /** @class */ (function (_super) {
  46646. __extends(ExecuteCodeAction, _super);
  46647. function ExecuteCodeAction(triggerOptions, func, condition) {
  46648. var _this = _super.call(this, triggerOptions, condition) || this;
  46649. _this.func = func;
  46650. return _this;
  46651. }
  46652. ExecuteCodeAction.prototype.execute = function (evt) {
  46653. this.func(evt);
  46654. };
  46655. return ExecuteCodeAction;
  46656. }(BABYLON.Action));
  46657. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46658. var SetParentAction = /** @class */ (function (_super) {
  46659. __extends(SetParentAction, _super);
  46660. function SetParentAction(triggerOptions, target, parent, condition) {
  46661. var _this = _super.call(this, triggerOptions, condition) || this;
  46662. _this._target = target;
  46663. _this._parent = parent;
  46664. return _this;
  46665. }
  46666. SetParentAction.prototype._prepare = function () {
  46667. };
  46668. SetParentAction.prototype.execute = function () {
  46669. if (this._target.parent === this._parent) {
  46670. return;
  46671. }
  46672. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46673. invertParentWorldMatrix.invert();
  46674. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46675. this._target.parent = this._parent;
  46676. };
  46677. SetParentAction.prototype.serialize = function (parent) {
  46678. return _super.prototype._serialize.call(this, {
  46679. name: "SetParentAction",
  46680. properties: [
  46681. BABYLON.Action._GetTargetProperty(this._target),
  46682. BABYLON.Action._GetTargetProperty(this._parent),
  46683. ]
  46684. }, parent);
  46685. };
  46686. return SetParentAction;
  46687. }(BABYLON.Action));
  46688. BABYLON.SetParentAction = SetParentAction;
  46689. var PlaySoundAction = /** @class */ (function (_super) {
  46690. __extends(PlaySoundAction, _super);
  46691. function PlaySoundAction(triggerOptions, sound, condition) {
  46692. var _this = _super.call(this, triggerOptions, condition) || this;
  46693. _this._sound = sound;
  46694. return _this;
  46695. }
  46696. PlaySoundAction.prototype._prepare = function () {
  46697. };
  46698. PlaySoundAction.prototype.execute = function () {
  46699. if (this._sound !== undefined)
  46700. this._sound.play();
  46701. };
  46702. PlaySoundAction.prototype.serialize = function (parent) {
  46703. return _super.prototype._serialize.call(this, {
  46704. name: "PlaySoundAction",
  46705. properties: [{ name: "sound", value: this._sound.name }]
  46706. }, parent);
  46707. };
  46708. return PlaySoundAction;
  46709. }(BABYLON.Action));
  46710. BABYLON.PlaySoundAction = PlaySoundAction;
  46711. var StopSoundAction = /** @class */ (function (_super) {
  46712. __extends(StopSoundAction, _super);
  46713. function StopSoundAction(triggerOptions, sound, condition) {
  46714. var _this = _super.call(this, triggerOptions, condition) || this;
  46715. _this._sound = sound;
  46716. return _this;
  46717. }
  46718. StopSoundAction.prototype._prepare = function () {
  46719. };
  46720. StopSoundAction.prototype.execute = function () {
  46721. if (this._sound !== undefined)
  46722. this._sound.stop();
  46723. };
  46724. StopSoundAction.prototype.serialize = function (parent) {
  46725. return _super.prototype._serialize.call(this, {
  46726. name: "StopSoundAction",
  46727. properties: [{ name: "sound", value: this._sound.name }]
  46728. }, parent);
  46729. };
  46730. return StopSoundAction;
  46731. }(BABYLON.Action));
  46732. BABYLON.StopSoundAction = StopSoundAction;
  46733. })(BABYLON || (BABYLON = {}));
  46734. //# sourceMappingURL=babylon.directActions.js.map
  46735. var BABYLON;
  46736. (function (BABYLON) {
  46737. var SpriteManager = /** @class */ (function () {
  46738. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  46739. if (epsilon === void 0) { epsilon = 0.01; }
  46740. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46741. this.name = name;
  46742. this.sprites = new Array();
  46743. this.renderingGroupId = 0;
  46744. this.layerMask = 0x0FFFFFFF;
  46745. this.fogEnabled = true;
  46746. this.isPickable = false;
  46747. /**
  46748. * An event triggered when the manager is disposed.
  46749. * @type {BABYLON.Observable}
  46750. */
  46751. this.onDisposeObservable = new BABYLON.Observable();
  46752. this._vertexBuffers = {};
  46753. this._capacity = capacity;
  46754. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  46755. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46756. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46757. if (cellSize.width && cellSize.height) {
  46758. this.cellWidth = cellSize.width;
  46759. this.cellHeight = cellSize.height;
  46760. }
  46761. else if (cellSize !== undefined) {
  46762. this.cellWidth = cellSize;
  46763. this.cellHeight = cellSize;
  46764. }
  46765. else {
  46766. return;
  46767. }
  46768. this._epsilon = epsilon;
  46769. this._scene = scene;
  46770. this._scene.spriteManagers.push(this);
  46771. var indices = [];
  46772. var index = 0;
  46773. for (var count = 0; count < capacity; count++) {
  46774. indices.push(index);
  46775. indices.push(index + 1);
  46776. indices.push(index + 2);
  46777. indices.push(index);
  46778. indices.push(index + 2);
  46779. indices.push(index + 3);
  46780. index += 4;
  46781. }
  46782. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46783. // VBO
  46784. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  46785. this._vertexData = new Float32Array(capacity * 16 * 4);
  46786. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  46787. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  46788. var options = this._buffer.createVertexBuffer("options", 4, 4);
  46789. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  46790. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  46791. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46792. this._vertexBuffers["options"] = options;
  46793. this._vertexBuffers["cellInfo"] = cellInfo;
  46794. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46795. // Effects
  46796. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  46797. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  46798. }
  46799. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  46800. set: function (callback) {
  46801. if (this._onDisposeObserver) {
  46802. this.onDisposeObservable.remove(this._onDisposeObserver);
  46803. }
  46804. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46805. },
  46806. enumerable: true,
  46807. configurable: true
  46808. });
  46809. Object.defineProperty(SpriteManager.prototype, "texture", {
  46810. get: function () {
  46811. return this._spriteTexture;
  46812. },
  46813. set: function (value) {
  46814. this._spriteTexture = value;
  46815. },
  46816. enumerable: true,
  46817. configurable: true
  46818. });
  46819. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  46820. var arrayOffset = index * 16;
  46821. if (offsetX === 0)
  46822. offsetX = this._epsilon;
  46823. else if (offsetX === 1)
  46824. offsetX = 1 - this._epsilon;
  46825. if (offsetY === 0)
  46826. offsetY = this._epsilon;
  46827. else if (offsetY === 1)
  46828. offsetY = 1 - this._epsilon;
  46829. this._vertexData[arrayOffset] = sprite.position.x;
  46830. this._vertexData[arrayOffset + 1] = sprite.position.y;
  46831. this._vertexData[arrayOffset + 2] = sprite.position.z;
  46832. this._vertexData[arrayOffset + 3] = sprite.angle;
  46833. this._vertexData[arrayOffset + 4] = sprite.width;
  46834. this._vertexData[arrayOffset + 5] = sprite.height;
  46835. this._vertexData[arrayOffset + 6] = offsetX;
  46836. this._vertexData[arrayOffset + 7] = offsetY;
  46837. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  46838. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  46839. var offset = (sprite.cellIndex / rowSize) >> 0;
  46840. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  46841. this._vertexData[arrayOffset + 11] = offset;
  46842. // Color
  46843. this._vertexData[arrayOffset + 12] = sprite.color.r;
  46844. this._vertexData[arrayOffset + 13] = sprite.color.g;
  46845. this._vertexData[arrayOffset + 14] = sprite.color.b;
  46846. this._vertexData[arrayOffset + 15] = sprite.color.a;
  46847. };
  46848. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  46849. var count = Math.min(this._capacity, this.sprites.length);
  46850. var min = BABYLON.Vector3.Zero();
  46851. var max = BABYLON.Vector3.Zero();
  46852. var distance = Number.MAX_VALUE;
  46853. var currentSprite = null;
  46854. var cameraSpacePosition = BABYLON.Vector3.Zero();
  46855. var cameraView = camera.getViewMatrix();
  46856. for (var index = 0; index < count; index++) {
  46857. var sprite = this.sprites[index];
  46858. if (!sprite) {
  46859. continue;
  46860. }
  46861. if (predicate) {
  46862. if (!predicate(sprite)) {
  46863. continue;
  46864. }
  46865. }
  46866. else if (!sprite.isPickable) {
  46867. continue;
  46868. }
  46869. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  46870. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  46871. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  46872. if (ray.intersectsBoxMinMax(min, max)) {
  46873. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  46874. if (distance > currentDistance) {
  46875. distance = currentDistance;
  46876. currentSprite = sprite;
  46877. if (fastCheck) {
  46878. break;
  46879. }
  46880. }
  46881. }
  46882. }
  46883. if (currentSprite) {
  46884. var result = new BABYLON.PickingInfo();
  46885. result.hit = true;
  46886. result.pickedSprite = currentSprite;
  46887. result.distance = distance;
  46888. return result;
  46889. }
  46890. return null;
  46891. };
  46892. SpriteManager.prototype.render = function () {
  46893. // Check
  46894. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  46895. return;
  46896. var engine = this._scene.getEngine();
  46897. var baseSize = this._spriteTexture.getBaseSize();
  46898. // Sprites
  46899. var deltaTime = engine.getDeltaTime();
  46900. var max = Math.min(this._capacity, this.sprites.length);
  46901. var rowSize = baseSize.width / this.cellWidth;
  46902. var offset = 0;
  46903. for (var index = 0; index < max; index++) {
  46904. var sprite = this.sprites[index];
  46905. if (!sprite) {
  46906. continue;
  46907. }
  46908. sprite._animate(deltaTime);
  46909. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  46910. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  46911. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  46912. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  46913. }
  46914. this._buffer.update(this._vertexData);
  46915. // Render
  46916. var effect = this._effectBase;
  46917. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46918. effect = this._effectFog;
  46919. }
  46920. engine.enableEffect(effect);
  46921. var viewMatrix = this._scene.getViewMatrix();
  46922. effect.setTexture("diffuseSampler", this._spriteTexture);
  46923. effect.setMatrix("view", viewMatrix);
  46924. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46925. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  46926. // Fog
  46927. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46928. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  46929. effect.setColor3("vFogColor", this._scene.fogColor);
  46930. }
  46931. // VBOs
  46932. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46933. // Draw order
  46934. engine.setDepthFunctionToLessOrEqual();
  46935. effect.setBool("alphaTest", true);
  46936. engine.setColorWrite(false);
  46937. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46938. engine.setColorWrite(true);
  46939. effect.setBool("alphaTest", false);
  46940. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46941. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46942. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46943. };
  46944. SpriteManager.prototype.dispose = function () {
  46945. if (this._buffer) {
  46946. this._buffer.dispose();
  46947. this._buffer = null;
  46948. }
  46949. if (this._indexBuffer) {
  46950. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46951. this._indexBuffer = null;
  46952. }
  46953. if (this._spriteTexture) {
  46954. this._spriteTexture.dispose();
  46955. this._spriteTexture = null;
  46956. }
  46957. // Remove from scene
  46958. var index = this._scene.spriteManagers.indexOf(this);
  46959. this._scene.spriteManagers.splice(index, 1);
  46960. // Callback
  46961. this.onDisposeObservable.notifyObservers(this);
  46962. this.onDisposeObservable.clear();
  46963. };
  46964. return SpriteManager;
  46965. }());
  46966. BABYLON.SpriteManager = SpriteManager;
  46967. })(BABYLON || (BABYLON = {}));
  46968. //# sourceMappingURL=babylon.spriteManager.js.map
  46969. var BABYLON;
  46970. (function (BABYLON) {
  46971. var Sprite = /** @class */ (function () {
  46972. function Sprite(name, manager) {
  46973. this.name = name;
  46974. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46975. this.width = 1.0;
  46976. this.height = 1.0;
  46977. this.angle = 0;
  46978. this.cellIndex = 0;
  46979. this.invertU = 0;
  46980. this.invertV = 0;
  46981. this.animations = new Array();
  46982. this.isPickable = false;
  46983. this._animationStarted = false;
  46984. this._loopAnimation = false;
  46985. this._fromIndex = 0;
  46986. this._toIndex = 0;
  46987. this._delay = 0;
  46988. this._direction = 1;
  46989. this._time = 0;
  46990. this._manager = manager;
  46991. this._manager.sprites.push(this);
  46992. this.position = BABYLON.Vector3.Zero();
  46993. }
  46994. Object.defineProperty(Sprite.prototype, "size", {
  46995. get: function () {
  46996. return this.width;
  46997. },
  46998. set: function (value) {
  46999. this.width = value;
  47000. this.height = value;
  47001. },
  47002. enumerable: true,
  47003. configurable: true
  47004. });
  47005. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  47006. this._fromIndex = from;
  47007. this._toIndex = to;
  47008. this._loopAnimation = loop;
  47009. this._delay = delay;
  47010. this._animationStarted = true;
  47011. this._direction = from < to ? 1 : -1;
  47012. this.cellIndex = from;
  47013. this._time = 0;
  47014. this._onAnimationEnd = onAnimationEnd;
  47015. };
  47016. Sprite.prototype.stopAnimation = function () {
  47017. this._animationStarted = false;
  47018. };
  47019. Sprite.prototype._animate = function (deltaTime) {
  47020. if (!this._animationStarted)
  47021. return;
  47022. this._time += deltaTime;
  47023. if (this._time > this._delay) {
  47024. this._time = this._time % this._delay;
  47025. this.cellIndex += this._direction;
  47026. if (this.cellIndex > this._toIndex) {
  47027. if (this._loopAnimation) {
  47028. this.cellIndex = this._fromIndex;
  47029. }
  47030. else {
  47031. this.cellIndex = this._toIndex;
  47032. this._animationStarted = false;
  47033. if (this._onAnimationEnd) {
  47034. this._onAnimationEnd();
  47035. }
  47036. if (this.disposeWhenFinishedAnimating) {
  47037. this.dispose();
  47038. }
  47039. }
  47040. }
  47041. }
  47042. };
  47043. Sprite.prototype.dispose = function () {
  47044. for (var i = 0; i < this._manager.sprites.length; i++) {
  47045. if (this._manager.sprites[i] == this) {
  47046. this._manager.sprites.splice(i, 1);
  47047. }
  47048. }
  47049. };
  47050. return Sprite;
  47051. }());
  47052. BABYLON.Sprite = Sprite;
  47053. })(BABYLON || (BABYLON = {}));
  47054. //# sourceMappingURL=babylon.sprite.js.map
  47055. var BABYLON;
  47056. (function (BABYLON) {
  47057. var IntersectionInfo = /** @class */ (function () {
  47058. function IntersectionInfo(bu, bv, distance) {
  47059. this.bu = bu;
  47060. this.bv = bv;
  47061. this.distance = distance;
  47062. this.faceId = 0;
  47063. this.subMeshId = 0;
  47064. }
  47065. return IntersectionInfo;
  47066. }());
  47067. BABYLON.IntersectionInfo = IntersectionInfo;
  47068. var PickingInfo = /** @class */ (function () {
  47069. function PickingInfo() {
  47070. this.hit = false;
  47071. this.distance = 0;
  47072. this.pickedPoint = null;
  47073. this.pickedMesh = null;
  47074. this.bu = 0;
  47075. this.bv = 0;
  47076. this.faceId = -1;
  47077. this.subMeshId = 0;
  47078. this.pickedSprite = null;
  47079. }
  47080. // Methods
  47081. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  47082. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  47083. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  47084. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  47085. return null;
  47086. }
  47087. var indices = this.pickedMesh.getIndices();
  47088. if (!indices) {
  47089. return null;
  47090. }
  47091. var result;
  47092. if (useVerticesNormals) {
  47093. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47094. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  47095. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  47096. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  47097. normal0 = normal0.scale(this.bu);
  47098. normal1 = normal1.scale(this.bv);
  47099. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  47100. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  47101. }
  47102. else {
  47103. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47104. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  47105. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  47106. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  47107. var p1p2 = vertex1.subtract(vertex2);
  47108. var p3p2 = vertex3.subtract(vertex2);
  47109. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  47110. }
  47111. if (useWorldCoordinates) {
  47112. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  47113. }
  47114. return BABYLON.Vector3.Normalize(result);
  47115. };
  47116. PickingInfo.prototype.getTextureCoordinates = function () {
  47117. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47118. return null;
  47119. }
  47120. var indices = this.pickedMesh.getIndices();
  47121. if (!indices) {
  47122. return null;
  47123. }
  47124. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47125. if (!uvs) {
  47126. return null;
  47127. }
  47128. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  47129. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  47130. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  47131. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  47132. uv1 = uv1.scale(this.bu);
  47133. uv2 = uv2.scale(this.bv);
  47134. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  47135. };
  47136. return PickingInfo;
  47137. }());
  47138. BABYLON.PickingInfo = PickingInfo;
  47139. })(BABYLON || (BABYLON = {}));
  47140. //# sourceMappingURL=babylon.pickingInfo.js.map
  47141. var BABYLON;
  47142. (function (BABYLON) {
  47143. var Ray = /** @class */ (function () {
  47144. function Ray(origin, direction, length) {
  47145. if (length === void 0) { length = Number.MAX_VALUE; }
  47146. this.origin = origin;
  47147. this.direction = direction;
  47148. this.length = length;
  47149. }
  47150. // Methods
  47151. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  47152. var d = 0.0;
  47153. var maxValue = Number.MAX_VALUE;
  47154. var inv;
  47155. var min;
  47156. var max;
  47157. var temp;
  47158. if (Math.abs(this.direction.x) < 0.0000001) {
  47159. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  47160. return false;
  47161. }
  47162. }
  47163. else {
  47164. inv = 1.0 / this.direction.x;
  47165. min = (minimum.x - this.origin.x) * inv;
  47166. max = (maximum.x - this.origin.x) * inv;
  47167. if (max === -Infinity) {
  47168. max = Infinity;
  47169. }
  47170. if (min > max) {
  47171. temp = min;
  47172. min = max;
  47173. max = temp;
  47174. }
  47175. d = Math.max(min, d);
  47176. maxValue = Math.min(max, maxValue);
  47177. if (d > maxValue) {
  47178. return false;
  47179. }
  47180. }
  47181. if (Math.abs(this.direction.y) < 0.0000001) {
  47182. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  47183. return false;
  47184. }
  47185. }
  47186. else {
  47187. inv = 1.0 / this.direction.y;
  47188. min = (minimum.y - this.origin.y) * inv;
  47189. max = (maximum.y - this.origin.y) * inv;
  47190. if (max === -Infinity) {
  47191. max = Infinity;
  47192. }
  47193. if (min > max) {
  47194. temp = min;
  47195. min = max;
  47196. max = temp;
  47197. }
  47198. d = Math.max(min, d);
  47199. maxValue = Math.min(max, maxValue);
  47200. if (d > maxValue) {
  47201. return false;
  47202. }
  47203. }
  47204. if (Math.abs(this.direction.z) < 0.0000001) {
  47205. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  47206. return false;
  47207. }
  47208. }
  47209. else {
  47210. inv = 1.0 / this.direction.z;
  47211. min = (minimum.z - this.origin.z) * inv;
  47212. max = (maximum.z - this.origin.z) * inv;
  47213. if (max === -Infinity) {
  47214. max = Infinity;
  47215. }
  47216. if (min > max) {
  47217. temp = min;
  47218. min = max;
  47219. max = temp;
  47220. }
  47221. d = Math.max(min, d);
  47222. maxValue = Math.min(max, maxValue);
  47223. if (d > maxValue) {
  47224. return false;
  47225. }
  47226. }
  47227. return true;
  47228. };
  47229. Ray.prototype.intersectsBox = function (box) {
  47230. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  47231. };
  47232. Ray.prototype.intersectsSphere = function (sphere) {
  47233. var x = sphere.center.x - this.origin.x;
  47234. var y = sphere.center.y - this.origin.y;
  47235. var z = sphere.center.z - this.origin.z;
  47236. var pyth = (x * x) + (y * y) + (z * z);
  47237. var rr = sphere.radius * sphere.radius;
  47238. if (pyth <= rr) {
  47239. return true;
  47240. }
  47241. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  47242. if (dot < 0.0) {
  47243. return false;
  47244. }
  47245. var temp = pyth - (dot * dot);
  47246. return temp <= rr;
  47247. };
  47248. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  47249. if (!this._edge1) {
  47250. this._edge1 = BABYLON.Vector3.Zero();
  47251. this._edge2 = BABYLON.Vector3.Zero();
  47252. this._pvec = BABYLON.Vector3.Zero();
  47253. this._tvec = BABYLON.Vector3.Zero();
  47254. this._qvec = BABYLON.Vector3.Zero();
  47255. }
  47256. vertex1.subtractToRef(vertex0, this._edge1);
  47257. vertex2.subtractToRef(vertex0, this._edge2);
  47258. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  47259. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  47260. if (det === 0) {
  47261. return null;
  47262. }
  47263. var invdet = 1 / det;
  47264. this.origin.subtractToRef(vertex0, this._tvec);
  47265. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  47266. if (bu < 0 || bu > 1.0) {
  47267. return null;
  47268. }
  47269. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  47270. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  47271. if (bv < 0 || bu + bv > 1.0) {
  47272. return null;
  47273. }
  47274. //check if the distance is longer than the predefined length.
  47275. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  47276. if (distance > this.length) {
  47277. return null;
  47278. }
  47279. return new BABYLON.IntersectionInfo(bu, bv, distance);
  47280. };
  47281. Ray.prototype.intersectsPlane = function (plane) {
  47282. var distance;
  47283. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  47284. if (Math.abs(result1) < 9.99999997475243E-07) {
  47285. return null;
  47286. }
  47287. else {
  47288. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  47289. distance = (-plane.d - result2) / result1;
  47290. if (distance < 0.0) {
  47291. if (distance < -9.99999997475243E-07) {
  47292. return null;
  47293. }
  47294. else {
  47295. return 0;
  47296. }
  47297. }
  47298. return distance;
  47299. }
  47300. };
  47301. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  47302. var tm = BABYLON.Tmp.Matrix[0];
  47303. mesh.getWorldMatrix().invertToRef(tm);
  47304. if (this._tmpRay) {
  47305. Ray.TransformToRef(this, tm, this._tmpRay);
  47306. }
  47307. else {
  47308. this._tmpRay = Ray.Transform(this, tm);
  47309. }
  47310. return mesh.intersects(this._tmpRay, fastCheck);
  47311. };
  47312. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  47313. if (results) {
  47314. results.length = 0;
  47315. }
  47316. else {
  47317. results = [];
  47318. }
  47319. for (var i = 0; i < meshes.length; i++) {
  47320. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  47321. if (pickInfo.hit) {
  47322. results.push(pickInfo);
  47323. }
  47324. }
  47325. results.sort(this._comparePickingInfo);
  47326. return results;
  47327. };
  47328. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  47329. if (pickingInfoA.distance < pickingInfoB.distance) {
  47330. return -1;
  47331. }
  47332. else if (pickingInfoA.distance > pickingInfoB.distance) {
  47333. return 1;
  47334. }
  47335. else {
  47336. return 0;
  47337. }
  47338. };
  47339. /**
  47340. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  47341. * @param sega the first point of the segment to test the intersection against
  47342. * @param segb the second point of the segment to test the intersection against
  47343. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  47344. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  47345. */
  47346. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  47347. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  47348. var u = segb.subtract(sega);
  47349. var v = rsegb.subtract(this.origin);
  47350. var w = sega.subtract(this.origin);
  47351. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  47352. var b = BABYLON.Vector3.Dot(u, v);
  47353. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  47354. var d = BABYLON.Vector3.Dot(u, w);
  47355. var e = BABYLON.Vector3.Dot(v, w);
  47356. var D = a * c - b * b; // always >= 0
  47357. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  47358. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  47359. // compute the line parameters of the two closest points
  47360. if (D < Ray.smallnum) {
  47361. sN = 0.0; // force using point P0 on segment S1
  47362. sD = 1.0; // to prevent possible division by 0.0 later
  47363. tN = e;
  47364. tD = c;
  47365. }
  47366. else {
  47367. sN = (b * e - c * d);
  47368. tN = (a * e - b * d);
  47369. if (sN < 0.0) {
  47370. sN = 0.0;
  47371. tN = e;
  47372. tD = c;
  47373. }
  47374. else if (sN > sD) {
  47375. sN = sD;
  47376. tN = e + b;
  47377. tD = c;
  47378. }
  47379. }
  47380. if (tN < 0.0) {
  47381. tN = 0.0;
  47382. // recompute sc for this edge
  47383. if (-d < 0.0) {
  47384. sN = 0.0;
  47385. }
  47386. else if (-d > a)
  47387. sN = sD;
  47388. else {
  47389. sN = -d;
  47390. sD = a;
  47391. }
  47392. }
  47393. else if (tN > tD) {
  47394. tN = tD;
  47395. // recompute sc for this edge
  47396. if ((-d + b) < 0.0) {
  47397. sN = 0;
  47398. }
  47399. else if ((-d + b) > a) {
  47400. sN = sD;
  47401. }
  47402. else {
  47403. sN = (-d + b);
  47404. sD = a;
  47405. }
  47406. }
  47407. // finally do the division to get sc and tc
  47408. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  47409. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  47410. // get the difference of the two closest points
  47411. var qtc = v.multiplyByFloats(tc, tc, tc);
  47412. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  47413. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  47414. if (isIntersected) {
  47415. return qtc.length();
  47416. }
  47417. return -1;
  47418. };
  47419. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47420. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  47421. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  47422. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  47423. this.direction.normalize();
  47424. return this;
  47425. };
  47426. // Statics
  47427. Ray.Zero = function () {
  47428. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  47429. };
  47430. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  47431. var result = Ray.Zero();
  47432. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  47433. };
  47434. /**
  47435. * 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
  47436. * transformed to the given world matrix.
  47437. * @param origin The origin point
  47438. * @param end The end point
  47439. * @param world a matrix to transform the ray to. Default is the identity matrix.
  47440. */
  47441. Ray.CreateNewFromTo = function (origin, end, world) {
  47442. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  47443. var direction = end.subtract(origin);
  47444. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  47445. direction.normalize();
  47446. return Ray.Transform(new Ray(origin, direction, length), world);
  47447. };
  47448. Ray.Transform = function (ray, matrix) {
  47449. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  47450. Ray.TransformToRef(ray, matrix, result);
  47451. return result;
  47452. };
  47453. Ray.TransformToRef = function (ray, matrix, result) {
  47454. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  47455. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  47456. result.length = ray.length;
  47457. var dir = result.direction;
  47458. var len = dir.length();
  47459. if (!(len === 0 || len === 1)) {
  47460. var num = 1.0 / len;
  47461. dir.x *= num;
  47462. dir.y *= num;
  47463. dir.z *= num;
  47464. result.length *= len;
  47465. }
  47466. };
  47467. Ray.smallnum = 0.00000001;
  47468. Ray.rayl = 10e8;
  47469. return Ray;
  47470. }());
  47471. BABYLON.Ray = Ray;
  47472. })(BABYLON || (BABYLON = {}));
  47473. //# sourceMappingURL=babylon.ray.js.map
  47474. var BABYLON;
  47475. (function (BABYLON) {
  47476. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  47477. if (boxMin.x > sphereCenter.x + sphereRadius)
  47478. return false;
  47479. if (sphereCenter.x - sphereRadius > boxMax.x)
  47480. return false;
  47481. if (boxMin.y > sphereCenter.y + sphereRadius)
  47482. return false;
  47483. if (sphereCenter.y - sphereRadius > boxMax.y)
  47484. return false;
  47485. if (boxMin.z > sphereCenter.z + sphereRadius)
  47486. return false;
  47487. if (sphereCenter.z - sphereRadius > boxMax.z)
  47488. return false;
  47489. return true;
  47490. };
  47491. var getLowestRoot = (function () {
  47492. var result = { root: 0, found: false };
  47493. return function (a, b, c, maxR) {
  47494. result.root = 0;
  47495. result.found = false;
  47496. var determinant = b * b - 4.0 * a * c;
  47497. if (determinant < 0)
  47498. return result;
  47499. var sqrtD = Math.sqrt(determinant);
  47500. var r1 = (-b - sqrtD) / (2.0 * a);
  47501. var r2 = (-b + sqrtD) / (2.0 * a);
  47502. if (r1 > r2) {
  47503. var temp = r2;
  47504. r2 = r1;
  47505. r1 = temp;
  47506. }
  47507. if (r1 > 0 && r1 < maxR) {
  47508. result.root = r1;
  47509. result.found = true;
  47510. return result;
  47511. }
  47512. if (r2 > 0 && r2 < maxR) {
  47513. result.root = r2;
  47514. result.found = true;
  47515. return result;
  47516. }
  47517. return result;
  47518. };
  47519. })();
  47520. var Collider = /** @class */ (function () {
  47521. function Collider() {
  47522. this._collisionPoint = BABYLON.Vector3.Zero();
  47523. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  47524. this._tempVector = BABYLON.Vector3.Zero();
  47525. this._tempVector2 = BABYLON.Vector3.Zero();
  47526. this._tempVector3 = BABYLON.Vector3.Zero();
  47527. this._tempVector4 = BABYLON.Vector3.Zero();
  47528. this._edge = BABYLON.Vector3.Zero();
  47529. this._baseToVertex = BABYLON.Vector3.Zero();
  47530. this._destinationPoint = BABYLON.Vector3.Zero();
  47531. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  47532. this._displacementVector = BABYLON.Vector3.Zero();
  47533. this._radius = BABYLON.Vector3.One();
  47534. this._retry = 0;
  47535. this._basePointWorld = BABYLON.Vector3.Zero();
  47536. this._velocityWorld = BABYLON.Vector3.Zero();
  47537. this._normalizedVelocity = BABYLON.Vector3.Zero();
  47538. this._collisionMask = -1;
  47539. }
  47540. Object.defineProperty(Collider.prototype, "collisionMask", {
  47541. get: function () {
  47542. return this._collisionMask;
  47543. },
  47544. set: function (mask) {
  47545. this._collisionMask = !isNaN(mask) ? mask : -1;
  47546. },
  47547. enumerable: true,
  47548. configurable: true
  47549. });
  47550. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  47551. /**
  47552. * Gets the plane normal used to compute the sliding response (in local space)
  47553. */
  47554. get: function () {
  47555. return this._slidePlaneNormal;
  47556. },
  47557. enumerable: true,
  47558. configurable: true
  47559. });
  47560. // Methods
  47561. Collider.prototype._initialize = function (source, dir, e) {
  47562. this._velocity = dir;
  47563. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  47564. this._basePoint = source;
  47565. source.multiplyToRef(this._radius, this._basePointWorld);
  47566. dir.multiplyToRef(this._radius, this._velocityWorld);
  47567. this._velocityWorldLength = this._velocityWorld.length();
  47568. this._epsilon = e;
  47569. this.collisionFound = false;
  47570. };
  47571. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  47572. pa.subtractToRef(point, this._tempVector);
  47573. pb.subtractToRef(point, this._tempVector2);
  47574. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  47575. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47576. if (d < 0)
  47577. return false;
  47578. pc.subtractToRef(point, this._tempVector3);
  47579. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  47580. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47581. if (d < 0)
  47582. return false;
  47583. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  47584. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47585. return d >= 0;
  47586. };
  47587. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  47588. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  47589. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  47590. if (distance > this._velocityWorldLength + max + sphereRadius) {
  47591. return false;
  47592. }
  47593. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  47594. return false;
  47595. return true;
  47596. };
  47597. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  47598. var t0;
  47599. var embeddedInPlane = false;
  47600. //defensive programming, actually not needed.
  47601. if (!trianglePlaneArray) {
  47602. trianglePlaneArray = [];
  47603. }
  47604. if (!trianglePlaneArray[faceIndex]) {
  47605. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  47606. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  47607. }
  47608. var trianglePlane = trianglePlaneArray[faceIndex];
  47609. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  47610. return;
  47611. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  47612. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  47613. if (normalDotVelocity == 0) {
  47614. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  47615. return;
  47616. embeddedInPlane = true;
  47617. t0 = 0;
  47618. }
  47619. else {
  47620. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47621. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47622. if (t0 > t1) {
  47623. var temp = t1;
  47624. t1 = t0;
  47625. t0 = temp;
  47626. }
  47627. if (t0 > 1.0 || t1 < 0.0)
  47628. return;
  47629. if (t0 < 0)
  47630. t0 = 0;
  47631. if (t0 > 1.0)
  47632. t0 = 1.0;
  47633. }
  47634. this._collisionPoint.copyFromFloats(0, 0, 0);
  47635. var found = false;
  47636. var t = 1.0;
  47637. if (!embeddedInPlane) {
  47638. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  47639. this._velocity.scaleToRef(t0, this._tempVector);
  47640. this._planeIntersectionPoint.addInPlace(this._tempVector);
  47641. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  47642. found = true;
  47643. t = t0;
  47644. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  47645. }
  47646. }
  47647. if (!found) {
  47648. var velocitySquaredLength = this._velocity.lengthSquared();
  47649. var a = velocitySquaredLength;
  47650. this._basePoint.subtractToRef(p1, this._tempVector);
  47651. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47652. var c = this._tempVector.lengthSquared() - 1.0;
  47653. var lowestRoot = getLowestRoot(a, b, c, t);
  47654. if (lowestRoot.found) {
  47655. t = lowestRoot.root;
  47656. found = true;
  47657. this._collisionPoint.copyFrom(p1);
  47658. }
  47659. this._basePoint.subtractToRef(p2, this._tempVector);
  47660. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47661. c = this._tempVector.lengthSquared() - 1.0;
  47662. lowestRoot = getLowestRoot(a, b, c, t);
  47663. if (lowestRoot.found) {
  47664. t = lowestRoot.root;
  47665. found = true;
  47666. this._collisionPoint.copyFrom(p2);
  47667. }
  47668. this._basePoint.subtractToRef(p3, this._tempVector);
  47669. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47670. c = this._tempVector.lengthSquared() - 1.0;
  47671. lowestRoot = getLowestRoot(a, b, c, t);
  47672. if (lowestRoot.found) {
  47673. t = lowestRoot.root;
  47674. found = true;
  47675. this._collisionPoint.copyFrom(p3);
  47676. }
  47677. p2.subtractToRef(p1, this._edge);
  47678. p1.subtractToRef(this._basePoint, this._baseToVertex);
  47679. var edgeSquaredLength = this._edge.lengthSquared();
  47680. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47681. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47682. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47683. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47684. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47685. lowestRoot = getLowestRoot(a, b, c, t);
  47686. if (lowestRoot.found) {
  47687. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47688. if (f >= 0.0 && f <= 1.0) {
  47689. t = lowestRoot.root;
  47690. found = true;
  47691. this._edge.scaleInPlace(f);
  47692. p1.addToRef(this._edge, this._collisionPoint);
  47693. }
  47694. }
  47695. p3.subtractToRef(p2, this._edge);
  47696. p2.subtractToRef(this._basePoint, this._baseToVertex);
  47697. edgeSquaredLength = this._edge.lengthSquared();
  47698. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47699. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47700. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47701. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47702. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47703. lowestRoot = getLowestRoot(a, b, c, t);
  47704. if (lowestRoot.found) {
  47705. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47706. if (f >= 0.0 && f <= 1.0) {
  47707. t = lowestRoot.root;
  47708. found = true;
  47709. this._edge.scaleInPlace(f);
  47710. p2.addToRef(this._edge, this._collisionPoint);
  47711. }
  47712. }
  47713. p1.subtractToRef(p3, this._edge);
  47714. p3.subtractToRef(this._basePoint, this._baseToVertex);
  47715. edgeSquaredLength = this._edge.lengthSquared();
  47716. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47717. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47718. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47719. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47720. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47721. lowestRoot = getLowestRoot(a, b, c, t);
  47722. if (lowestRoot.found) {
  47723. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47724. if (f >= 0.0 && f <= 1.0) {
  47725. t = lowestRoot.root;
  47726. found = true;
  47727. this._edge.scaleInPlace(f);
  47728. p3.addToRef(this._edge, this._collisionPoint);
  47729. }
  47730. }
  47731. }
  47732. if (found) {
  47733. var distToCollision = t * this._velocity.length();
  47734. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  47735. if (!this.intersectionPoint) {
  47736. this.intersectionPoint = this._collisionPoint.clone();
  47737. }
  47738. else {
  47739. this.intersectionPoint.copyFrom(this._collisionPoint);
  47740. }
  47741. this._nearestDistance = distToCollision;
  47742. this.collisionFound = true;
  47743. }
  47744. }
  47745. };
  47746. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  47747. for (var i = indexStart; i < indexEnd; i += 3) {
  47748. var p1 = pts[indices[i] - decal];
  47749. var p2 = pts[indices[i + 1] - decal];
  47750. var p3 = pts[indices[i + 2] - decal];
  47751. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  47752. }
  47753. };
  47754. Collider.prototype._getResponse = function (pos, vel) {
  47755. pos.addToRef(vel, this._destinationPoint);
  47756. vel.scaleInPlace((this._nearestDistance / vel.length()));
  47757. this._basePoint.addToRef(vel, pos);
  47758. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  47759. this._slidePlaneNormal.normalize();
  47760. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  47761. pos.addInPlace(this._displacementVector);
  47762. this.intersectionPoint.addInPlace(this._displacementVector);
  47763. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47764. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47765. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47766. };
  47767. return Collider;
  47768. }());
  47769. BABYLON.Collider = Collider;
  47770. })(BABYLON || (BABYLON = {}));
  47771. //# sourceMappingURL=babylon.collider.js.map
  47772. var BABYLON;
  47773. (function (BABYLON) {
  47774. //WebWorker code will be inserted to this variable.
  47775. BABYLON.CollisionWorker = "";
  47776. var WorkerTaskType;
  47777. (function (WorkerTaskType) {
  47778. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  47779. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  47780. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  47781. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  47782. var WorkerReplyType;
  47783. (function (WorkerReplyType) {
  47784. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  47785. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  47786. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  47787. var CollisionCoordinatorWorker = /** @class */ (function () {
  47788. function CollisionCoordinatorWorker() {
  47789. var _this = this;
  47790. this._scaledPosition = BABYLON.Vector3.Zero();
  47791. this._scaledVelocity = BABYLON.Vector3.Zero();
  47792. this.onMeshUpdated = function (transformNode) {
  47793. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  47794. };
  47795. this.onGeometryUpdated = function (geometry) {
  47796. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  47797. };
  47798. this._afterRender = function () {
  47799. if (!_this._init)
  47800. return;
  47801. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  47802. return;
  47803. }
  47804. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  47805. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  47806. if (_this._runningUpdated > 4) {
  47807. return;
  47808. }
  47809. ++_this._runningUpdated;
  47810. var payload = {
  47811. updatedMeshes: _this._addUpdateMeshesList,
  47812. updatedGeometries: _this._addUpdateGeometriesList,
  47813. removedGeometries: _this._toRemoveGeometryArray,
  47814. removedMeshes: _this._toRemoveMeshesArray
  47815. };
  47816. var message = {
  47817. payload: payload,
  47818. taskType: WorkerTaskType.UPDATE
  47819. };
  47820. var serializable = [];
  47821. for (var id in payload.updatedGeometries) {
  47822. if (payload.updatedGeometries.hasOwnProperty(id)) {
  47823. //prepare transferables
  47824. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  47825. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  47826. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  47827. }
  47828. }
  47829. _this._worker.postMessage(message, serializable);
  47830. _this._addUpdateMeshesList = {};
  47831. _this._addUpdateGeometriesList = {};
  47832. _this._toRemoveGeometryArray = [];
  47833. _this._toRemoveMeshesArray = [];
  47834. };
  47835. this._onMessageFromWorker = function (e) {
  47836. var returnData = e.data;
  47837. if (returnData.error != WorkerReplyType.SUCCESS) {
  47838. //TODO what errors can be returned from the worker?
  47839. BABYLON.Tools.Warn("error returned from worker!");
  47840. return;
  47841. }
  47842. switch (returnData.taskType) {
  47843. case WorkerTaskType.INIT:
  47844. _this._init = true;
  47845. //Update the worked with ALL of the scene's current state
  47846. _this._scene.meshes.forEach(function (mesh) {
  47847. _this.onMeshAdded(mesh);
  47848. });
  47849. _this._scene.getGeometries().forEach(function (geometry) {
  47850. _this.onGeometryAdded(geometry);
  47851. });
  47852. break;
  47853. case WorkerTaskType.UPDATE:
  47854. _this._runningUpdated--;
  47855. break;
  47856. case WorkerTaskType.COLLIDE:
  47857. var returnPayload = returnData.payload;
  47858. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  47859. return;
  47860. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  47861. if (callback) {
  47862. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  47863. if (mesh) {
  47864. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  47865. }
  47866. }
  47867. //cleanup
  47868. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  47869. break;
  47870. }
  47871. };
  47872. this._collisionsCallbackArray = [];
  47873. this._init = false;
  47874. this._runningUpdated = 0;
  47875. this._addUpdateMeshesList = {};
  47876. this._addUpdateGeometriesList = {};
  47877. this._toRemoveGeometryArray = [];
  47878. this._toRemoveMeshesArray = [];
  47879. }
  47880. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47881. if (!this._init)
  47882. return;
  47883. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  47884. return;
  47885. position.divideToRef(collider._radius, this._scaledPosition);
  47886. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47887. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  47888. var payload = {
  47889. collider: {
  47890. position: this._scaledPosition.asArray(),
  47891. velocity: this._scaledVelocity.asArray(),
  47892. radius: collider._radius.asArray()
  47893. },
  47894. collisionId: collisionIndex,
  47895. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  47896. maximumRetry: maximumRetry
  47897. };
  47898. var message = {
  47899. payload: payload,
  47900. taskType: WorkerTaskType.COLLIDE
  47901. };
  47902. this._worker.postMessage(message);
  47903. };
  47904. CollisionCoordinatorWorker.prototype.init = function (scene) {
  47905. this._scene = scene;
  47906. this._scene.registerAfterRender(this._afterRender);
  47907. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  47908. this._worker = new Worker(workerUrl);
  47909. this._worker.onmessage = this._onMessageFromWorker;
  47910. var message = {
  47911. payload: {},
  47912. taskType: WorkerTaskType.INIT
  47913. };
  47914. this._worker.postMessage(message);
  47915. };
  47916. CollisionCoordinatorWorker.prototype.destroy = function () {
  47917. this._scene.unregisterAfterRender(this._afterRender);
  47918. this._worker.terminate();
  47919. };
  47920. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  47921. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  47922. this.onMeshUpdated(mesh);
  47923. };
  47924. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  47925. this._toRemoveMeshesArray.push(mesh.uniqueId);
  47926. };
  47927. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  47928. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  47929. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47930. this.onGeometryUpdated(geometry);
  47931. };
  47932. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47933. this._toRemoveGeometryArray.push(geometry.id);
  47934. };
  47935. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47936. var submeshes = [];
  47937. if (mesh.subMeshes) {
  47938. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47939. var boundingInfo = sm.getBoundingInfo();
  47940. return {
  47941. position: idx,
  47942. verticesStart: sm.verticesStart,
  47943. verticesCount: sm.verticesCount,
  47944. indexStart: sm.indexStart,
  47945. indexCount: sm.indexCount,
  47946. hasMaterial: !!sm.getMaterial(),
  47947. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47948. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47949. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47950. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47951. };
  47952. });
  47953. }
  47954. var geometryId = null;
  47955. if (mesh instanceof BABYLON.Mesh) {
  47956. var geometry = mesh.geometry;
  47957. geometryId = geometry ? geometry.id : null;
  47958. }
  47959. else if (mesh instanceof BABYLON.InstancedMesh) {
  47960. var geometry = mesh.sourceMesh.geometry;
  47961. geometryId = geometry ? geometry.id : null;
  47962. }
  47963. var boundingInfo = mesh.getBoundingInfo();
  47964. return {
  47965. uniqueId: mesh.uniqueId,
  47966. id: mesh.id,
  47967. name: mesh.name,
  47968. geometryId: geometryId,
  47969. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47970. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47971. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47972. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47973. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47974. subMeshes: submeshes,
  47975. checkCollisions: mesh.checkCollisions
  47976. };
  47977. };
  47978. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47979. return {
  47980. id: geometry.id,
  47981. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47982. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47983. indices: new Uint32Array(geometry.getIndices() || []),
  47984. };
  47985. };
  47986. return CollisionCoordinatorWorker;
  47987. }());
  47988. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47989. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47990. function CollisionCoordinatorLegacy() {
  47991. this._scaledPosition = BABYLON.Vector3.Zero();
  47992. this._scaledVelocity = BABYLON.Vector3.Zero();
  47993. this._finalPosition = BABYLON.Vector3.Zero();
  47994. }
  47995. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47996. position.divideToRef(collider._radius, this._scaledPosition);
  47997. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47998. collider.collidedMesh = null;
  47999. collider._retry = 0;
  48000. collider._initialVelocity = this._scaledVelocity;
  48001. collider._initialPosition = this._scaledPosition;
  48002. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  48003. this._finalPosition.multiplyInPlace(collider._radius);
  48004. //run the callback
  48005. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  48006. };
  48007. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  48008. this._scene = scene;
  48009. };
  48010. CollisionCoordinatorLegacy.prototype.destroy = function () {
  48011. //Legacy need no destruction method.
  48012. };
  48013. //No update in legacy mode
  48014. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  48015. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  48016. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  48017. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  48018. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  48019. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  48020. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  48021. if (excludedMesh === void 0) { excludedMesh = null; }
  48022. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  48023. if (collider._retry >= maximumRetry) {
  48024. finalPosition.copyFrom(position);
  48025. return;
  48026. }
  48027. // Check if this is a mesh else camera or -1
  48028. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  48029. collider._initialize(position, velocity, closeDistance);
  48030. // Check all meshes
  48031. for (var index = 0; index < this._scene.meshes.length; index++) {
  48032. var mesh = this._scene.meshes[index];
  48033. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  48034. mesh._checkCollision(collider);
  48035. }
  48036. }
  48037. if (!collider.collisionFound) {
  48038. position.addToRef(velocity, finalPosition);
  48039. return;
  48040. }
  48041. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  48042. collider._getResponse(position, velocity);
  48043. }
  48044. if (velocity.length() <= closeDistance) {
  48045. finalPosition.copyFrom(position);
  48046. return;
  48047. }
  48048. collider._retry++;
  48049. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  48050. };
  48051. return CollisionCoordinatorLegacy;
  48052. }());
  48053. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  48054. })(BABYLON || (BABYLON = {}));
  48055. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  48056. var BABYLON;
  48057. (function (BABYLON) {
  48058. /**
  48059. * A particle represents one of the element emitted by a particle system.
  48060. * This is mainly define by its coordinates, direction, velocity and age.
  48061. */
  48062. var Particle = /** @class */ (function () {
  48063. /**
  48064. * Creates a new instance of @see Particle
  48065. * @param particleSystem the particle system the particle belongs to
  48066. */
  48067. function Particle(particleSystem) {
  48068. this.particleSystem = particleSystem;
  48069. /**
  48070. * The world position of the particle in the scene.
  48071. */
  48072. this.position = BABYLON.Vector3.Zero();
  48073. /**
  48074. * The world direction of the particle in the scene.
  48075. */
  48076. this.direction = BABYLON.Vector3.Zero();
  48077. /**
  48078. * The color of the particle.
  48079. */
  48080. this.color = new BABYLON.Color4(0, 0, 0, 0);
  48081. /**
  48082. * The color change of the particle per step.
  48083. */
  48084. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  48085. /**
  48086. * Defines how long will the life of the particle be.
  48087. */
  48088. this.lifeTime = 1.0;
  48089. /**
  48090. * The current age of the particle.
  48091. */
  48092. this.age = 0;
  48093. /**
  48094. * The current size of the particle.
  48095. */
  48096. this.size = 0;
  48097. /**
  48098. * The current angle of the particle.
  48099. */
  48100. this.angle = 0;
  48101. /**
  48102. * Defines how fast is the angle changing.
  48103. */
  48104. this.angularSpeed = 0;
  48105. /**
  48106. * Defines the cell index used by the particle to be rendered from a sprite.
  48107. */
  48108. this.cellIndex = 0;
  48109. this._currentFrameCounter = 0;
  48110. if (!this.particleSystem.isAnimationSheetEnabled) {
  48111. return;
  48112. }
  48113. this.cellIndex = this.particleSystem.startSpriteCellID;
  48114. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  48115. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  48116. }
  48117. else {
  48118. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  48119. }
  48120. }
  48121. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  48122. // (ageOffset / scaledUpdateSpeed) / available cells
  48123. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  48124. this._currentFrameCounter += scaledUpdateSpeed;
  48125. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  48126. this._currentFrameCounter = 0;
  48127. this.cellIndex++;
  48128. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48129. this.cellIndex = this.particleSystem.endSpriteCellID;
  48130. }
  48131. }
  48132. };
  48133. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  48134. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  48135. this.cellIndex++;
  48136. this._currentFrameCounter = 0;
  48137. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  48138. if (this.particleSystem.spriteCellLoop) {
  48139. this.cellIndex = this.particleSystem.startSpriteCellID;
  48140. }
  48141. else {
  48142. this.cellIndex = this.particleSystem.endSpriteCellID;
  48143. }
  48144. }
  48145. }
  48146. else {
  48147. this._currentFrameCounter++;
  48148. }
  48149. };
  48150. /**
  48151. * Copy the properties of particle to another one.
  48152. * @param other the particle to copy the information to.
  48153. */
  48154. Particle.prototype.copyTo = function (other) {
  48155. other.position.copyFrom(this.position);
  48156. other.direction.copyFrom(this.direction);
  48157. other.color.copyFrom(this.color);
  48158. other.colorStep.copyFrom(this.colorStep);
  48159. other.lifeTime = this.lifeTime;
  48160. other.age = this.age;
  48161. other.size = this.size;
  48162. other.angle = this.angle;
  48163. other.angularSpeed = this.angularSpeed;
  48164. other.particleSystem = this.particleSystem;
  48165. other.cellIndex = this.cellIndex;
  48166. };
  48167. return Particle;
  48168. }());
  48169. BABYLON.Particle = Particle;
  48170. })(BABYLON || (BABYLON = {}));
  48171. //# sourceMappingURL=babylon.particle.js.map
  48172. var BABYLON;
  48173. (function (BABYLON) {
  48174. /**
  48175. * This represents a particle system in Babylon.
  48176. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  48177. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  48178. * @example https://doc.babylonjs.com/babylon101/particles
  48179. */
  48180. var ParticleSystem = /** @class */ (function () {
  48181. /**
  48182. * Instantiates a particle system.
  48183. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  48184. * @param name The name of the particle system
  48185. * @param capacity The max number of particles alive at the same time
  48186. * @param scene The scene the particle system belongs to
  48187. * @param customEffect a custom effect used to change the way particles are rendered by default
  48188. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  48189. * @param epsilon Offset used to render the particles
  48190. */
  48191. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  48192. if (customEffect === void 0) { customEffect = null; }
  48193. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  48194. if (epsilon === void 0) { epsilon = 0.01; }
  48195. var _this = this;
  48196. /**
  48197. * List of animations used by the particle system.
  48198. */
  48199. this.animations = [];
  48200. /**
  48201. * The rendering group used by the Particle system to chose when to render.
  48202. */
  48203. this.renderingGroupId = 0;
  48204. /**
  48205. * The emitter represents the Mesh or position we are attaching the particle system to.
  48206. */
  48207. this.emitter = null;
  48208. /**
  48209. * The density of particles, the rate of particle flow
  48210. */
  48211. this.emitRate = 10;
  48212. /**
  48213. * If you want to launch only a few particles at once, that can be done, as well.
  48214. */
  48215. this.manualEmitCount = -1;
  48216. /**
  48217. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  48218. */
  48219. this.updateSpeed = 0.01;
  48220. /**
  48221. * The amount of time the particle system is running (depends of the overall speed above).
  48222. */
  48223. this.targetStopDuration = 0;
  48224. /**
  48225. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  48226. */
  48227. this.disposeOnStop = false;
  48228. /**
  48229. * Minimum power of emitting particles.
  48230. */
  48231. this.minEmitPower = 1;
  48232. /**
  48233. * Maximum power of emitting particles.
  48234. */
  48235. this.maxEmitPower = 1;
  48236. /**
  48237. * Minimum life time of emitting particles.
  48238. */
  48239. this.minLifeTime = 1;
  48240. /**
  48241. * Maximum life time of emitting particles.
  48242. */
  48243. this.maxLifeTime = 1;
  48244. /**
  48245. * Minimum Size of emitting particles.
  48246. */
  48247. this.minSize = 1;
  48248. /**
  48249. * Maximum Size of emitting particles.
  48250. */
  48251. this.maxSize = 1;
  48252. /**
  48253. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  48254. */
  48255. this.minAngularSpeed = 0;
  48256. /**
  48257. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  48258. */
  48259. this.maxAngularSpeed = 0;
  48260. /**
  48261. * The layer mask we are rendering the particles through.
  48262. */
  48263. this.layerMask = 0x0FFFFFFF;
  48264. /**
  48265. * This can help using your own shader to render the particle system.
  48266. * The according effect will be created
  48267. */
  48268. this.customShader = null;
  48269. /**
  48270. * By default particle system starts as soon as they are created. This prevents the
  48271. * automatic start to happen and let you decide when to start emitting particles.
  48272. */
  48273. this.preventAutoStart = false;
  48274. /**
  48275. * Callback triggered when the particle animation is ending.
  48276. */
  48277. this.onAnimationEnd = null;
  48278. /**
  48279. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  48280. */
  48281. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  48282. /**
  48283. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  48284. * to override the particles.
  48285. */
  48286. this.forceDepthWrite = false;
  48287. /**
  48288. * You can use gravity if you want to give an orientation to your particles.
  48289. */
  48290. this.gravity = BABYLON.Vector3.Zero();
  48291. /**
  48292. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48293. */
  48294. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  48295. /**
  48296. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48297. */
  48298. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  48299. /**
  48300. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48301. */
  48302. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  48303. /**
  48304. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48305. */
  48306. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48307. /**
  48308. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48309. */
  48310. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48311. /**
  48312. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  48313. */
  48314. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48315. /**
  48316. * Color the particle will have at the end of its lifetime.
  48317. */
  48318. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  48319. /**
  48320. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  48321. */
  48322. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48323. /**
  48324. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  48325. */
  48326. this.spriteCellLoop = true;
  48327. /**
  48328. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  48329. */
  48330. this.spriteCellChangeSpeed = 0;
  48331. /**
  48332. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  48333. */
  48334. this.startSpriteCellID = 0;
  48335. /**
  48336. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  48337. */
  48338. this.endSpriteCellID = 0;
  48339. /**
  48340. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  48341. */
  48342. this.spriteCellWidth = 0;
  48343. /**
  48344. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  48345. */
  48346. this.spriteCellHeight = 0;
  48347. /**
  48348. * An event triggered when the system is disposed.
  48349. */
  48350. this.onDisposeObservable = new BABYLON.Observable();
  48351. this._particles = new Array();
  48352. this._stockParticles = new Array();
  48353. this._newPartsExcess = 0;
  48354. this._vertexBuffers = {};
  48355. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  48356. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  48357. this._scaledDirection = BABYLON.Vector3.Zero();
  48358. this._scaledGravity = BABYLON.Vector3.Zero();
  48359. this._currentRenderId = -1;
  48360. this._started = false;
  48361. this._stopped = false;
  48362. this._actualFrame = 0;
  48363. this._vertexBufferSize = 11;
  48364. this._appendParticleVertexes = null;
  48365. this.id = name;
  48366. this.name = name;
  48367. this._capacity = capacity;
  48368. this._epsilon = epsilon;
  48369. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  48370. if (isAnimationSheetEnabled) {
  48371. this._vertexBufferSize = 12;
  48372. }
  48373. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48374. this._customEffect = customEffect;
  48375. scene.particleSystems.push(this);
  48376. this._createIndexBuffer();
  48377. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  48378. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  48379. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  48380. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  48381. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  48382. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  48383. if (this._isAnimationSheetEnabled) {
  48384. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  48385. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  48386. }
  48387. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48388. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48389. this._vertexBuffers["options"] = options;
  48390. // Default behaviors
  48391. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  48392. this.updateFunction = function (particles) {
  48393. for (var index = 0; index < particles.length; index++) {
  48394. var particle = particles[index];
  48395. particle.age += _this._scaledUpdateSpeed;
  48396. if (particle.age >= particle.lifeTime) {
  48397. _this.recycleParticle(particle);
  48398. index--;
  48399. continue;
  48400. }
  48401. else {
  48402. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  48403. particle.color.addInPlace(_this._scaledColorStep);
  48404. if (particle.color.a < 0)
  48405. particle.color.a = 0;
  48406. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  48407. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  48408. particle.position.addInPlace(_this._scaledDirection);
  48409. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  48410. particle.direction.addInPlace(_this._scaledGravity);
  48411. if (_this._isAnimationSheetEnabled) {
  48412. particle.updateCellIndex(_this._scaledUpdateSpeed);
  48413. }
  48414. }
  48415. }
  48416. };
  48417. }
  48418. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  48419. /**
  48420. * Sets a callback that will be triggered when the system is disposed.
  48421. */
  48422. set: function (callback) {
  48423. if (this._onDisposeObserver) {
  48424. this.onDisposeObservable.remove(this._onDisposeObserver);
  48425. }
  48426. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48427. },
  48428. enumerable: true,
  48429. configurable: true
  48430. });
  48431. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  48432. /**
  48433. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  48434. */
  48435. get: function () {
  48436. return this._isAnimationSheetEnabled;
  48437. },
  48438. enumerable: true,
  48439. configurable: true
  48440. });
  48441. ParticleSystem.prototype._createIndexBuffer = function () {
  48442. var indices = [];
  48443. var index = 0;
  48444. for (var count = 0; count < this._capacity; count++) {
  48445. indices.push(index);
  48446. indices.push(index + 1);
  48447. indices.push(index + 2);
  48448. indices.push(index);
  48449. indices.push(index + 2);
  48450. indices.push(index + 3);
  48451. index += 4;
  48452. }
  48453. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  48454. };
  48455. /**
  48456. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  48457. * Its lifetime will start back at 0.
  48458. * @param particle The particle to recycle
  48459. */
  48460. ParticleSystem.prototype.recycleParticle = function (particle) {
  48461. var lastParticle = this._particles.pop();
  48462. if (lastParticle !== particle) {
  48463. lastParticle.copyTo(particle);
  48464. this._stockParticles.push(lastParticle);
  48465. }
  48466. };
  48467. /**
  48468. * Gets the maximum number of particles active at the same time.
  48469. * @returns The max number of active particles.
  48470. */
  48471. ParticleSystem.prototype.getCapacity = function () {
  48472. return this._capacity;
  48473. };
  48474. /**
  48475. * Gets Wether there are still active particles in the system.
  48476. * @returns True if it is alive, otherwise false.
  48477. */
  48478. ParticleSystem.prototype.isAlive = function () {
  48479. return this._alive;
  48480. };
  48481. /**
  48482. * Gets Wether the system has been started.
  48483. * @returns True if it has been started, otherwise false.
  48484. */
  48485. ParticleSystem.prototype.isStarted = function () {
  48486. return this._started;
  48487. };
  48488. /**
  48489. * Starts the particle system and begins to emit.
  48490. */
  48491. ParticleSystem.prototype.start = function () {
  48492. this._started = true;
  48493. this._stopped = false;
  48494. this._actualFrame = 0;
  48495. };
  48496. /**
  48497. * Stops the particle system.
  48498. */
  48499. ParticleSystem.prototype.stop = function () {
  48500. this._stopped = true;
  48501. };
  48502. /**
  48503. * @ignore (for internal use only)
  48504. */
  48505. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  48506. var offset = index * this._vertexBufferSize;
  48507. this._vertexData[offset] = particle.position.x;
  48508. this._vertexData[offset + 1] = particle.position.y;
  48509. this._vertexData[offset + 2] = particle.position.z;
  48510. this._vertexData[offset + 3] = particle.color.r;
  48511. this._vertexData[offset + 4] = particle.color.g;
  48512. this._vertexData[offset + 5] = particle.color.b;
  48513. this._vertexData[offset + 6] = particle.color.a;
  48514. this._vertexData[offset + 7] = particle.angle;
  48515. this._vertexData[offset + 8] = particle.size;
  48516. this._vertexData[offset + 9] = offsetX;
  48517. this._vertexData[offset + 10] = offsetY;
  48518. };
  48519. /**
  48520. * @ignore (for internal use only)
  48521. */
  48522. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  48523. if (offsetX === 0)
  48524. offsetX = this._epsilon;
  48525. else if (offsetX === 1)
  48526. offsetX = 1 - this._epsilon;
  48527. if (offsetY === 0)
  48528. offsetY = this._epsilon;
  48529. else if (offsetY === 1)
  48530. offsetY = 1 - this._epsilon;
  48531. var offset = index * this._vertexBufferSize;
  48532. this._vertexData[offset] = particle.position.x;
  48533. this._vertexData[offset + 1] = particle.position.y;
  48534. this._vertexData[offset + 2] = particle.position.z;
  48535. this._vertexData[offset + 3] = particle.color.r;
  48536. this._vertexData[offset + 4] = particle.color.g;
  48537. this._vertexData[offset + 5] = particle.color.b;
  48538. this._vertexData[offset + 6] = particle.color.a;
  48539. this._vertexData[offset + 7] = particle.angle;
  48540. this._vertexData[offset + 8] = particle.size;
  48541. this._vertexData[offset + 9] = offsetX;
  48542. this._vertexData[offset + 10] = offsetY;
  48543. this._vertexData[offset + 11] = particle.cellIndex;
  48544. };
  48545. ParticleSystem.prototype._update = function (newParticles) {
  48546. // Update current
  48547. this._alive = this._particles.length > 0;
  48548. this.updateFunction(this._particles);
  48549. // Add new ones
  48550. var worldMatrix;
  48551. if (this.emitter.position) {
  48552. var emitterMesh = this.emitter;
  48553. worldMatrix = emitterMesh.getWorldMatrix();
  48554. }
  48555. else {
  48556. var emitterPosition = this.emitter;
  48557. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  48558. }
  48559. var particle;
  48560. for (var index = 0; index < newParticles; index++) {
  48561. if (this._particles.length === this._capacity) {
  48562. break;
  48563. }
  48564. if (this._stockParticles.length !== 0) {
  48565. particle = this._stockParticles.pop();
  48566. particle.age = 0;
  48567. particle.cellIndex = this.startSpriteCellID;
  48568. }
  48569. else {
  48570. particle = new BABYLON.Particle(this);
  48571. }
  48572. this._particles.push(particle);
  48573. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  48574. if (this.startPositionFunction) {
  48575. this.startPositionFunction(worldMatrix, particle.position, particle);
  48576. }
  48577. else {
  48578. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  48579. }
  48580. if (this.startDirectionFunction) {
  48581. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48582. }
  48583. else {
  48584. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48585. }
  48586. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  48587. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  48588. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  48589. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  48590. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  48591. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  48592. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  48593. }
  48594. };
  48595. ParticleSystem.prototype._getEffect = function () {
  48596. if (this._customEffect) {
  48597. return this._customEffect;
  48598. }
  48599. ;
  48600. var defines = [];
  48601. if (this._scene.clipPlane) {
  48602. defines.push("#define CLIPPLANE");
  48603. }
  48604. if (this._isAnimationSheetEnabled) {
  48605. defines.push("#define ANIMATESHEET");
  48606. }
  48607. // Effect
  48608. var join = defines.join("\n");
  48609. if (this._cachedDefines !== join) {
  48610. this._cachedDefines = join;
  48611. var attributesNamesOrOptions;
  48612. var effectCreationOption;
  48613. if (this._isAnimationSheetEnabled) {
  48614. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  48615. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  48616. }
  48617. else {
  48618. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  48619. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  48620. }
  48621. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  48622. }
  48623. return this._effect;
  48624. };
  48625. /**
  48626. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48627. */
  48628. ParticleSystem.prototype.animate = function () {
  48629. if (!this._started)
  48630. return;
  48631. var effect = this._getEffect();
  48632. // Check
  48633. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  48634. return;
  48635. if (this._currentRenderId === this._scene.getRenderId()) {
  48636. return;
  48637. }
  48638. this._currentRenderId = this._scene.getRenderId();
  48639. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  48640. // determine the number of particles we need to create
  48641. var newParticles;
  48642. if (this.manualEmitCount > -1) {
  48643. newParticles = this.manualEmitCount;
  48644. this._newPartsExcess = 0;
  48645. this.manualEmitCount = 0;
  48646. }
  48647. else {
  48648. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  48649. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  48650. }
  48651. if (this._newPartsExcess > 1.0) {
  48652. newParticles += this._newPartsExcess >> 0;
  48653. this._newPartsExcess -= this._newPartsExcess >> 0;
  48654. }
  48655. this._alive = false;
  48656. if (!this._stopped) {
  48657. this._actualFrame += this._scaledUpdateSpeed;
  48658. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  48659. this.stop();
  48660. }
  48661. else {
  48662. newParticles = 0;
  48663. }
  48664. this._update(newParticles);
  48665. // Stopped?
  48666. if (this._stopped) {
  48667. if (!this._alive) {
  48668. this._started = false;
  48669. if (this.onAnimationEnd) {
  48670. this.onAnimationEnd();
  48671. }
  48672. if (this.disposeOnStop) {
  48673. this._scene._toBeDisposed.push(this);
  48674. }
  48675. }
  48676. }
  48677. // Animation sheet
  48678. if (this._isAnimationSheetEnabled) {
  48679. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  48680. }
  48681. else {
  48682. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  48683. }
  48684. // Update VBO
  48685. var offset = 0;
  48686. for (var index = 0; index < this._particles.length; index++) {
  48687. var particle = this._particles[index];
  48688. this._appendParticleVertexes(offset, particle);
  48689. offset += 4;
  48690. }
  48691. if (this._vertexBuffer) {
  48692. this._vertexBuffer.update(this._vertexData);
  48693. }
  48694. };
  48695. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  48696. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  48697. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  48698. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  48699. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  48700. };
  48701. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  48702. this._appendParticleVertex(offset++, particle, 0, 0);
  48703. this._appendParticleVertex(offset++, particle, 1, 0);
  48704. this._appendParticleVertex(offset++, particle, 1, 1);
  48705. this._appendParticleVertex(offset++, particle, 0, 1);
  48706. };
  48707. /**
  48708. * Rebuilds the particle system.
  48709. */
  48710. ParticleSystem.prototype.rebuild = function () {
  48711. this._createIndexBuffer();
  48712. if (this._vertexBuffer) {
  48713. this._vertexBuffer._rebuild();
  48714. }
  48715. };
  48716. /**
  48717. * Renders the particle system in its current state.
  48718. * @returns the current number of particles.
  48719. */
  48720. ParticleSystem.prototype.render = function () {
  48721. var effect = this._getEffect();
  48722. // Check
  48723. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  48724. return 0;
  48725. var engine = this._scene.getEngine();
  48726. // Render
  48727. engine.enableEffect(effect);
  48728. engine.setState(false);
  48729. var viewMatrix = this._scene.getViewMatrix();
  48730. effect.setTexture("diffuseSampler", this.particleTexture);
  48731. effect.setMatrix("view", viewMatrix);
  48732. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48733. if (this._isAnimationSheetEnabled) {
  48734. var baseSize = this.particleTexture.getBaseSize();
  48735. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  48736. }
  48737. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  48738. if (this._scene.clipPlane) {
  48739. var clipPlane = this._scene.clipPlane;
  48740. var invView = viewMatrix.clone();
  48741. invView.invert();
  48742. effect.setMatrix("invView", invView);
  48743. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  48744. }
  48745. // VBOs
  48746. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48747. // Draw order
  48748. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  48749. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48750. }
  48751. else {
  48752. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48753. }
  48754. if (this.forceDepthWrite) {
  48755. engine.setDepthWrite(true);
  48756. }
  48757. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  48758. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48759. return this._particles.length;
  48760. };
  48761. /**
  48762. * Disposes the particle system and free the associated resources.
  48763. */
  48764. ParticleSystem.prototype.dispose = function () {
  48765. if (this._vertexBuffer) {
  48766. this._vertexBuffer.dispose();
  48767. this._vertexBuffer = null;
  48768. }
  48769. if (this._indexBuffer) {
  48770. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48771. this._indexBuffer = null;
  48772. }
  48773. if (this.particleTexture) {
  48774. this.particleTexture.dispose();
  48775. this.particleTexture = null;
  48776. }
  48777. // Remove from scene
  48778. var index = this._scene.particleSystems.indexOf(this);
  48779. if (index > -1) {
  48780. this._scene.particleSystems.splice(index, 1);
  48781. }
  48782. // Callback
  48783. this.onDisposeObservable.notifyObservers(this);
  48784. this.onDisposeObservable.clear();
  48785. };
  48786. /**
  48787. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  48788. * @param radius The radius of the sphere to emit from
  48789. * @returns the emitter
  48790. */
  48791. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  48792. if (radius === void 0) { radius = 1; }
  48793. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  48794. this.particleEmitterType = particleEmitter;
  48795. return particleEmitter;
  48796. };
  48797. /**
  48798. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  48799. * @param radius The radius of the sphere to emit from
  48800. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  48801. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  48802. * @returns the emitter
  48803. */
  48804. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  48805. if (radius === void 0) { radius = 1; }
  48806. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  48807. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  48808. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  48809. this.particleEmitterType = particleEmitter;
  48810. return particleEmitter;
  48811. };
  48812. /**
  48813. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  48814. * @param radius The radius of the cone to emit from
  48815. * @param angle The base angle of the cone
  48816. * @returns the emitter
  48817. */
  48818. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  48819. if (radius === void 0) { radius = 1; }
  48820. if (angle === void 0) { angle = Math.PI / 4; }
  48821. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  48822. this.particleEmitterType = particleEmitter;
  48823. return particleEmitter;
  48824. };
  48825. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  48826. /**
  48827. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  48828. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  48829. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  48830. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48831. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48832. * @returns the emitter
  48833. */
  48834. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  48835. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  48836. this.direction1 = direction1;
  48837. this.direction2 = direction2;
  48838. this.minEmitBox = minEmitBox;
  48839. this.maxEmitBox = maxEmitBox;
  48840. this.particleEmitterType = particleEmitter;
  48841. return particleEmitter;
  48842. };
  48843. /**
  48844. * Clones the particle system.
  48845. * @param name The name of the cloned object
  48846. * @param newEmitter The new emitter to use
  48847. * @returns the cloned particle system
  48848. */
  48849. ParticleSystem.prototype.clone = function (name, newEmitter) {
  48850. var custom = null;
  48851. var program = null;
  48852. if (this.customShader != null) {
  48853. program = this.customShader;
  48854. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48855. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48856. }
  48857. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  48858. result.customShader = program;
  48859. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  48860. if (newEmitter === undefined) {
  48861. newEmitter = this.emitter;
  48862. }
  48863. result.emitter = newEmitter;
  48864. if (this.particleTexture) {
  48865. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  48866. }
  48867. if (!this.preventAutoStart) {
  48868. result.start();
  48869. }
  48870. return result;
  48871. };
  48872. /**
  48873. * Serializes the particle system to a JSON object.
  48874. * @returns the JSON object
  48875. */
  48876. ParticleSystem.prototype.serialize = function () {
  48877. var serializationObject = {};
  48878. serializationObject.name = this.name;
  48879. serializationObject.id = this.id;
  48880. // Emitter
  48881. if (this.emitter.position) {
  48882. var emitterMesh = this.emitter;
  48883. serializationObject.emitterId = emitterMesh.id;
  48884. }
  48885. else {
  48886. var emitterPosition = this.emitter;
  48887. serializationObject.emitter = emitterPosition.asArray();
  48888. }
  48889. serializationObject.capacity = this.getCapacity();
  48890. if (this.particleTexture) {
  48891. serializationObject.textureName = this.particleTexture.name;
  48892. }
  48893. // Animations
  48894. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  48895. // Particle system
  48896. serializationObject.minAngularSpeed = this.minAngularSpeed;
  48897. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  48898. serializationObject.minSize = this.minSize;
  48899. serializationObject.maxSize = this.maxSize;
  48900. serializationObject.minEmitPower = this.minEmitPower;
  48901. serializationObject.maxEmitPower = this.maxEmitPower;
  48902. serializationObject.minLifeTime = this.minLifeTime;
  48903. serializationObject.maxLifeTime = this.maxLifeTime;
  48904. serializationObject.emitRate = this.emitRate;
  48905. serializationObject.minEmitBox = this.minEmitBox.asArray();
  48906. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  48907. serializationObject.gravity = this.gravity.asArray();
  48908. serializationObject.direction1 = this.direction1.asArray();
  48909. serializationObject.direction2 = this.direction2.asArray();
  48910. serializationObject.color1 = this.color1.asArray();
  48911. serializationObject.color2 = this.color2.asArray();
  48912. serializationObject.colorDead = this.colorDead.asArray();
  48913. serializationObject.updateSpeed = this.updateSpeed;
  48914. serializationObject.targetStopDuration = this.targetStopDuration;
  48915. serializationObject.textureMask = this.textureMask.asArray();
  48916. serializationObject.blendMode = this.blendMode;
  48917. serializationObject.customShader = this.customShader;
  48918. serializationObject.preventAutoStart = this.preventAutoStart;
  48919. serializationObject.startSpriteCellID = this.startSpriteCellID;
  48920. serializationObject.endSpriteCellID = this.endSpriteCellID;
  48921. serializationObject.spriteCellLoop = this.spriteCellLoop;
  48922. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  48923. serializationObject.spriteCellWidth = this.spriteCellWidth;
  48924. serializationObject.spriteCellHeight = this.spriteCellHeight;
  48925. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  48926. return serializationObject;
  48927. };
  48928. /**
  48929. * Parses a JSON object to create a particle system.
  48930. * @param parsedParticleSystem The JSON object to parse
  48931. * @param scene The scene to create the particle system in
  48932. * @param rootUrl The root url to use to load external dependencies like texture
  48933. * @returns the Parsed particle system
  48934. */
  48935. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48936. var name = parsedParticleSystem.name;
  48937. var custom = null;
  48938. var program = null;
  48939. if (parsedParticleSystem.customShader) {
  48940. program = parsedParticleSystem.customShader;
  48941. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48942. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48943. }
  48944. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48945. particleSystem.customShader = program;
  48946. if (parsedParticleSystem.id) {
  48947. particleSystem.id = parsedParticleSystem.id;
  48948. }
  48949. // Auto start
  48950. if (parsedParticleSystem.preventAutoStart) {
  48951. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48952. }
  48953. // Texture
  48954. if (parsedParticleSystem.textureName) {
  48955. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48956. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48957. }
  48958. // Emitter
  48959. if (parsedParticleSystem.emitterId) {
  48960. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48961. }
  48962. else {
  48963. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48964. }
  48965. // Animations
  48966. if (parsedParticleSystem.animations) {
  48967. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48968. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48969. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48970. }
  48971. }
  48972. if (parsedParticleSystem.autoAnimate) {
  48973. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48974. }
  48975. // Particle system
  48976. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48977. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48978. particleSystem.minSize = parsedParticleSystem.minSize;
  48979. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48980. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48981. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48982. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48983. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48984. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48985. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48986. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48987. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48988. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48989. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48990. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48991. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48992. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48993. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48994. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48995. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48996. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48997. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48998. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48999. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  49000. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  49001. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  49002. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  49003. if (!particleSystem.preventAutoStart) {
  49004. particleSystem.start();
  49005. }
  49006. return particleSystem;
  49007. };
  49008. /**
  49009. * Source color is added to the destination color without alpha affecting the result.
  49010. */
  49011. ParticleSystem.BLENDMODE_ONEONE = 0;
  49012. /**
  49013. * Blend current color and particle color using particle’s alpha.
  49014. */
  49015. ParticleSystem.BLENDMODE_STANDARD = 1;
  49016. return ParticleSystem;
  49017. }());
  49018. BABYLON.ParticleSystem = ParticleSystem;
  49019. })(BABYLON || (BABYLON = {}));
  49020. //# sourceMappingURL=babylon.particleSystem.js.map
  49021. var BABYLON;
  49022. (function (BABYLON) {
  49023. /**
  49024. * Particle emitter emitting particles from the inside of a box.
  49025. * It emits the particles randomly between 2 given directions.
  49026. */
  49027. var BoxParticleEmitter = /** @class */ (function () {
  49028. // to be updated like the rest of emitters when breaking changes.
  49029. // all property should be come public variables and passed through constructor.
  49030. /**
  49031. * Creates a new instance of @see BoxParticleEmitter
  49032. * @param _particleSystem the particle system associated with the emitter
  49033. */
  49034. function BoxParticleEmitter(_particleSystem) {
  49035. this._particleSystem = _particleSystem;
  49036. }
  49037. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  49038. /**
  49039. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49040. */
  49041. get: function () {
  49042. return this._particleSystem.direction1;
  49043. },
  49044. /**
  49045. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49046. */
  49047. set: function (value) {
  49048. this._particleSystem.direction1 = value;
  49049. },
  49050. enumerable: true,
  49051. configurable: true
  49052. });
  49053. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  49054. /**
  49055. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49056. */
  49057. get: function () {
  49058. return this._particleSystem.direction2;
  49059. },
  49060. /**
  49061. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49062. */
  49063. set: function (value) {
  49064. this._particleSystem.direction2 = value;
  49065. },
  49066. enumerable: true,
  49067. configurable: true
  49068. });
  49069. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  49070. /**
  49071. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  49072. */
  49073. get: function () {
  49074. return this._particleSystem.minEmitBox;
  49075. },
  49076. /**
  49077. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  49078. */
  49079. set: function (value) {
  49080. this._particleSystem.minEmitBox = value;
  49081. },
  49082. enumerable: true,
  49083. configurable: true
  49084. });
  49085. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  49086. /**
  49087. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  49088. */
  49089. get: function () {
  49090. return this._particleSystem.maxEmitBox;
  49091. },
  49092. /**
  49093. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  49094. */
  49095. set: function (value) {
  49096. this._particleSystem.maxEmitBox = value;
  49097. },
  49098. enumerable: true,
  49099. configurable: true
  49100. });
  49101. /**
  49102. * Called by the particle System when the direction is computed for the created particle.
  49103. * @param emitPower is the power of the particle (speed)
  49104. * @param worldMatrix is the world matrix of the particle system
  49105. * @param directionToUpdate is the direction vector to update with the result
  49106. * @param particle is the particle we are computed the direction for
  49107. */
  49108. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49109. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49110. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49111. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49112. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49113. };
  49114. /**
  49115. * Called by the particle System when the position is computed for the created particle.
  49116. * @param worldMatrix is the world matrix of the particle system
  49117. * @param positionToUpdate is the position vector to update with the result
  49118. * @param particle is the particle we are computed the position for
  49119. */
  49120. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49121. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  49122. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  49123. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  49124. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49125. };
  49126. /**
  49127. * Clones the current emitter and returns a copy of it
  49128. * @returns the new emitter
  49129. */
  49130. BoxParticleEmitter.prototype.clone = function () {
  49131. var newOne = new BoxParticleEmitter(this._particleSystem);
  49132. BABYLON.Tools.DeepCopy(this, newOne);
  49133. return newOne;
  49134. };
  49135. return BoxParticleEmitter;
  49136. }());
  49137. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  49138. })(BABYLON || (BABYLON = {}));
  49139. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  49140. var BABYLON;
  49141. (function (BABYLON) {
  49142. /**
  49143. * Particle emitter emitting particles from the inside of a cone.
  49144. * It emits the particles alongside the cone volume from the base to the particle.
  49145. * The emission direction might be randomized.
  49146. */
  49147. var ConeParticleEmitter = /** @class */ (function () {
  49148. /**
  49149. * Creates a new instance of @see ConeParticleEmitter
  49150. * @param radius the radius of the emission cone
  49151. * @param angles the cone base angle
  49152. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49153. */
  49154. function ConeParticleEmitter(radius,
  49155. /**
  49156. * The radius of the emission cone.
  49157. */
  49158. angle,
  49159. /**
  49160. * The cone base angle.
  49161. */
  49162. directionRandomizer) {
  49163. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49164. this.angle = angle;
  49165. this.directionRandomizer = directionRandomizer;
  49166. this.radius = radius;
  49167. }
  49168. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  49169. /**
  49170. * Gets the radius of the emission cone.
  49171. */
  49172. get: function () {
  49173. return this._radius;
  49174. },
  49175. /**
  49176. * Sets the radius of the emission cone.
  49177. */
  49178. set: function (value) {
  49179. this._radius = value;
  49180. if (this.angle !== 0) {
  49181. this._height = value / Math.tan(this.angle / 2);
  49182. }
  49183. else {
  49184. this._height = 1;
  49185. }
  49186. },
  49187. enumerable: true,
  49188. configurable: true
  49189. });
  49190. /**
  49191. * Called by the particle System when the direction is computed for the created particle.
  49192. * @param emitPower is the power of the particle (speed)
  49193. * @param worldMatrix is the world matrix of the particle system
  49194. * @param directionToUpdate is the direction vector to update with the result
  49195. * @param particle is the particle we are computed the direction for
  49196. */
  49197. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49198. if (this.angle === 0) {
  49199. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  49200. }
  49201. else {
  49202. // measure the direction Vector from the emitter to the particle.
  49203. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49204. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49205. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49206. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49207. direction.x += randX;
  49208. direction.y += randY;
  49209. direction.z += randZ;
  49210. direction.normalize();
  49211. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49212. }
  49213. };
  49214. /**
  49215. * Called by the particle System when the position is computed for the created particle.
  49216. * @param worldMatrix is the world matrix of the particle system
  49217. * @param positionToUpdate is the position vector to update with the result
  49218. * @param particle is the particle we are computed the position for
  49219. */
  49220. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49221. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  49222. var h = BABYLON.Scalar.RandomRange(0, 1);
  49223. // Better distribution in a cone at normal angles.
  49224. h = 1 - h * h;
  49225. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  49226. radius = radius * h / this._height;
  49227. var randX = radius * Math.sin(s);
  49228. var randZ = radius * Math.cos(s);
  49229. var randY = h;
  49230. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49231. };
  49232. /**
  49233. * Clones the current emitter and returns a copy of it
  49234. * @returns the new emitter
  49235. */
  49236. ConeParticleEmitter.prototype.clone = function () {
  49237. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  49238. BABYLON.Tools.DeepCopy(this, newOne);
  49239. return newOne;
  49240. };
  49241. return ConeParticleEmitter;
  49242. }());
  49243. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  49244. })(BABYLON || (BABYLON = {}));
  49245. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  49246. var BABYLON;
  49247. (function (BABYLON) {
  49248. /**
  49249. * Particle emitter emitting particles from the inside of a sphere.
  49250. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  49251. */
  49252. var SphereParticleEmitter = /** @class */ (function () {
  49253. /**
  49254. * Creates a new instance of @see SphereParticleEmitter
  49255. * @param radius the radius of the emission sphere
  49256. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  49257. */
  49258. function SphereParticleEmitter(
  49259. /**
  49260. * The radius of the emission sphere.
  49261. */
  49262. radius,
  49263. /**
  49264. * How much to randomize the particle direction [0-1].
  49265. */
  49266. directionRandomizer) {
  49267. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  49268. this.radius = radius;
  49269. this.directionRandomizer = directionRandomizer;
  49270. }
  49271. /**
  49272. * Called by the particle System when the direction is computed for the created particle.
  49273. * @param emitPower is the power of the particle (speed)
  49274. * @param worldMatrix is the world matrix of the particle system
  49275. * @param directionToUpdate is the direction vector to update with the result
  49276. * @param particle is the particle we are computed the direction for
  49277. */
  49278. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49279. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  49280. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49281. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49282. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  49283. direction.x += randX;
  49284. direction.y += randY;
  49285. direction.z += randZ;
  49286. direction.normalize();
  49287. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  49288. };
  49289. /**
  49290. * Called by the particle System when the position is computed for the created particle.
  49291. * @param worldMatrix is the world matrix of the particle system
  49292. * @param positionToUpdate is the position vector to update with the result
  49293. * @param particle is the particle we are computed the position for
  49294. */
  49295. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  49296. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  49297. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  49298. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  49299. var randY = this.radius * Math.cos(theta);
  49300. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  49301. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  49302. };
  49303. /**
  49304. * Clones the current emitter and returns a copy of it
  49305. * @returns the new emitter
  49306. */
  49307. SphereParticleEmitter.prototype.clone = function () {
  49308. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  49309. BABYLON.Tools.DeepCopy(this, newOne);
  49310. return newOne;
  49311. };
  49312. return SphereParticleEmitter;
  49313. }());
  49314. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  49315. /**
  49316. * Particle emitter emitting particles from the inside of a sphere.
  49317. * It emits the particles randomly between two vectors.
  49318. */
  49319. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  49320. __extends(SphereDirectedParticleEmitter, _super);
  49321. /**
  49322. * Creates a new instance of @see SphereDirectedParticleEmitter
  49323. * @param radius the radius of the emission sphere
  49324. * @param direction1 the min limit of the emission direction
  49325. * @param direction2 the max limit of the emission direction
  49326. */
  49327. function SphereDirectedParticleEmitter(radius,
  49328. /**
  49329. * The min limit of the emission direction.
  49330. */
  49331. direction1,
  49332. /**
  49333. * The max limit of the emission direction.
  49334. */
  49335. direction2) {
  49336. var _this = _super.call(this, radius) || this;
  49337. _this.direction1 = direction1;
  49338. _this.direction2 = direction2;
  49339. return _this;
  49340. }
  49341. /**
  49342. * Called by the particle System when the direction is computed for the created particle.
  49343. * @param emitPower is the power of the particle (speed)
  49344. * @param worldMatrix is the world matrix of the particle system
  49345. * @param directionToUpdate is the direction vector to update with the result
  49346. * @param particle is the particle we are computed the direction for
  49347. */
  49348. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  49349. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  49350. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  49351. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  49352. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  49353. };
  49354. /**
  49355. * Clones the current emitter and returns a copy of it
  49356. * @returns the new emitter
  49357. */
  49358. SphereDirectedParticleEmitter.prototype.clone = function () {
  49359. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  49360. BABYLON.Tools.DeepCopy(this, newOne);
  49361. return newOne;
  49362. };
  49363. return SphereDirectedParticleEmitter;
  49364. }(SphereParticleEmitter));
  49365. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  49366. })(BABYLON || (BABYLON = {}));
  49367. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  49368. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  49369. var BABYLON;
  49370. (function (BABYLON) {
  49371. /**
  49372. * Represents one particle of a solid particle system.
  49373. * @see SolidParticleSystem
  49374. */
  49375. var SolidParticle = /** @class */ (function () {
  49376. /**
  49377. * Creates a Solid Particle object.
  49378. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49379. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49380. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49381. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  49382. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  49383. * @param shapeId (integer) is the model shape identifier in the SPS.
  49384. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49385. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  49386. */
  49387. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49388. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  49389. /**
  49390. * particle global index
  49391. */
  49392. this.idx = 0;
  49393. /**
  49394. * The color of the particle
  49395. */
  49396. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49397. /**
  49398. * The world space position of the particle.
  49399. */
  49400. this.position = BABYLON.Vector3.Zero();
  49401. /**
  49402. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  49403. */
  49404. this.rotation = BABYLON.Vector3.Zero();
  49405. /**
  49406. * The scaling of the particle.
  49407. */
  49408. this.scaling = BABYLON.Vector3.One();
  49409. /**
  49410. * The uvs of the particle.
  49411. */
  49412. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  49413. /**
  49414. * The current speed of the particle.
  49415. */
  49416. this.velocity = BABYLON.Vector3.Zero();
  49417. /**
  49418. * The pivot point in the particle local space.
  49419. */
  49420. this.pivot = BABYLON.Vector3.Zero();
  49421. /**
  49422. * Is the particle active or not ?
  49423. */
  49424. this.alive = true;
  49425. /**
  49426. * Is the particle visible or not ?
  49427. */
  49428. this.isVisible = true;
  49429. /**
  49430. * Index of this particle in the global "positions" array (Internal use)
  49431. */
  49432. this._pos = 0;
  49433. /**
  49434. * Index of this particle in the global "indices" array (Internal use)
  49435. */
  49436. this._ind = 0;
  49437. /**
  49438. * ModelShape id of this particle
  49439. */
  49440. this.shapeId = 0;
  49441. /**
  49442. * Index of the particle in its shape id (Internal use)
  49443. */
  49444. this.idxInShape = 0;
  49445. /**
  49446. * Still set as invisible in order to skip useless computations (Internal use)
  49447. */
  49448. this._stillInvisible = false;
  49449. /**
  49450. * Last computed particle rotation matrix
  49451. */
  49452. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  49453. this.idx = particleIndex;
  49454. this._pos = positionIndex;
  49455. this._ind = indiceIndex;
  49456. this._model = model;
  49457. this.shapeId = shapeId;
  49458. this.idxInShape = idxInShape;
  49459. this._sps = sps;
  49460. if (modelBoundingInfo) {
  49461. this._modelBoundingInfo = modelBoundingInfo;
  49462. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49463. }
  49464. }
  49465. Object.defineProperty(SolidParticle.prototype, "scale", {
  49466. /**
  49467. * Legacy support, changed scale to scaling
  49468. */
  49469. get: function () {
  49470. return this.scaling;
  49471. },
  49472. /**
  49473. * Legacy support, changed scale to scaling
  49474. */
  49475. set: function (scale) {
  49476. this.scaling = scale;
  49477. },
  49478. enumerable: true,
  49479. configurable: true
  49480. });
  49481. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49482. /**
  49483. * Legacy support, changed quaternion to rotationQuaternion
  49484. */
  49485. get: function () {
  49486. return this.rotationQuaternion;
  49487. },
  49488. /**
  49489. * Legacy support, changed quaternion to rotationQuaternion
  49490. */
  49491. set: function (q) {
  49492. this.rotationQuaternion = q;
  49493. },
  49494. enumerable: true,
  49495. configurable: true
  49496. });
  49497. /**
  49498. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49499. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49500. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  49501. * @returns true if it intersects
  49502. */
  49503. SolidParticle.prototype.intersectsMesh = function (target) {
  49504. if (!this._boundingInfo || !target._boundingInfo) {
  49505. return false;
  49506. }
  49507. if (this._sps._bSphereOnly) {
  49508. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49509. }
  49510. return this._boundingInfo.intersects(target._boundingInfo, false);
  49511. };
  49512. return SolidParticle;
  49513. }());
  49514. BABYLON.SolidParticle = SolidParticle;
  49515. /**
  49516. * Represents the shape of the model used by one particle of a solid particle system.
  49517. * SPS internal tool, don't use it manually.
  49518. * @see SolidParticleSystem
  49519. */
  49520. var ModelShape = /** @class */ (function () {
  49521. /**
  49522. * 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.
  49523. * SPS internal tool, don't use it manually.
  49524. * @ignore
  49525. */
  49526. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  49527. /**
  49528. * length of the shape in the model indices array (internal use)
  49529. */
  49530. this._indicesLength = 0;
  49531. this.shapeID = id;
  49532. this._shape = shape;
  49533. this._indicesLength = indicesLength;
  49534. this._shapeUV = shapeUV;
  49535. this._positionFunction = posFunction;
  49536. this._vertexFunction = vtxFunction;
  49537. }
  49538. return ModelShape;
  49539. }());
  49540. BABYLON.ModelShape = ModelShape;
  49541. /**
  49542. * Represents a Depth Sorted Particle in the solid particle system.
  49543. * @see SolidParticleSystem
  49544. */
  49545. var DepthSortedParticle = /** @class */ (function () {
  49546. function DepthSortedParticle() {
  49547. /**
  49548. * Index of the particle in the "indices" array
  49549. */
  49550. this.ind = 0;
  49551. /**
  49552. * Length of the particle shape in the "indices" array
  49553. */
  49554. this.indicesLength = 0;
  49555. /**
  49556. * Squared distance from the particle to the camera
  49557. */
  49558. this.sqDistance = 0.0;
  49559. }
  49560. return DepthSortedParticle;
  49561. }());
  49562. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49563. })(BABYLON || (BABYLON = {}));
  49564. //# sourceMappingURL=babylon.solidParticle.js.map
  49565. var BABYLON;
  49566. (function (BABYLON) {
  49567. /**
  49568. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49569. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  49570. * The SPS is also a particle system. It provides some methods to manage the particles.
  49571. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49572. *
  49573. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49574. */
  49575. var SolidParticleSystem = /** @class */ (function () {
  49576. /**
  49577. * Creates a SPS (Solid Particle System) object.
  49578. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49579. * @param scene (Scene) is the scene in which the SPS is added.
  49580. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  49581. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  49582. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  49583. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  49584. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49585. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49586. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49587. */
  49588. function SolidParticleSystem(name, scene, options) {
  49589. /**
  49590. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49591. * Example : var p = SPS.particles[i];
  49592. */
  49593. this.particles = new Array();
  49594. /**
  49595. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49596. */
  49597. this.nbParticles = 0;
  49598. /**
  49599. * If the particles must ever face the camera (default false). Useful for planar particles.
  49600. */
  49601. this.billboard = false;
  49602. /**
  49603. * Recompute normals when adding a shape
  49604. */
  49605. this.recomputeNormals = true;
  49606. /**
  49607. * This a counter ofr your own usage. It's not set by any SPS functions.
  49608. */
  49609. this.counter = 0;
  49610. /**
  49611. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49612. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49613. */
  49614. this.vars = {};
  49615. /**
  49616. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  49617. */
  49618. this._bSphereOnly = false;
  49619. /**
  49620. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  49621. */
  49622. this._bSphereRadiusFactor = 1.0;
  49623. this._positions = new Array();
  49624. this._indices = new Array();
  49625. this._normals = new Array();
  49626. this._colors = new Array();
  49627. this._uvs = new Array();
  49628. this._index = 0; // indices index
  49629. this._updatable = true;
  49630. this._pickable = false;
  49631. this._isVisibilityBoxLocked = false;
  49632. this._alwaysVisible = false;
  49633. this._depthSort = false;
  49634. this._shapeCounter = 0;
  49635. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  49636. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49637. this._computeParticleColor = true;
  49638. this._computeParticleTexture = true;
  49639. this._computeParticleRotation = true;
  49640. this._computeParticleVertex = false;
  49641. this._computeBoundingBox = false;
  49642. this._depthSortParticles = true;
  49643. this._cam_axisZ = BABYLON.Vector3.Zero();
  49644. this._cam_axisY = BABYLON.Vector3.Zero();
  49645. this._cam_axisX = BABYLON.Vector3.Zero();
  49646. this._axisZ = BABYLON.Axis.Z;
  49647. this._camDir = BABYLON.Vector3.Zero();
  49648. this._camInvertedPosition = BABYLON.Vector3.Zero();
  49649. this._rotMatrix = new BABYLON.Matrix();
  49650. this._invertMatrix = new BABYLON.Matrix();
  49651. this._rotated = BABYLON.Vector3.Zero();
  49652. this._quaternion = new BABYLON.Quaternion();
  49653. this._vertex = BABYLON.Vector3.Zero();
  49654. this._normal = BABYLON.Vector3.Zero();
  49655. this._yaw = 0.0;
  49656. this._pitch = 0.0;
  49657. this._roll = 0.0;
  49658. this._halfroll = 0.0;
  49659. this._halfpitch = 0.0;
  49660. this._halfyaw = 0.0;
  49661. this._sinRoll = 0.0;
  49662. this._cosRoll = 0.0;
  49663. this._sinPitch = 0.0;
  49664. this._cosPitch = 0.0;
  49665. this._sinYaw = 0.0;
  49666. this._cosYaw = 0.0;
  49667. this._mustUnrotateFixedNormals = false;
  49668. this._minimum = BABYLON.Tmp.Vector3[0];
  49669. this._maximum = BABYLON.Tmp.Vector3[1];
  49670. this._minBbox = BABYLON.Tmp.Vector3[4];
  49671. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49672. this._particlesIntersect = false;
  49673. this._depthSortFunction = function (p1, p2) {
  49674. return (p2.sqDistance - p1.sqDistance);
  49675. };
  49676. this._needs32Bits = false;
  49677. this.name = name;
  49678. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49679. this._camera = scene.activeCamera;
  49680. this._pickable = options ? options.isPickable : false;
  49681. this._depthSort = options ? options.enableDepthSort : false;
  49682. this._particlesIntersect = options ? options.particleIntersection : false;
  49683. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49684. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49685. if (options && options.updatable) {
  49686. this._updatable = options.updatable;
  49687. }
  49688. else {
  49689. this._updatable = true;
  49690. }
  49691. if (this._pickable) {
  49692. this.pickedParticles = [];
  49693. }
  49694. if (this._depthSort) {
  49695. this.depthSortedParticles = [];
  49696. }
  49697. }
  49698. /**
  49699. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49700. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49701. * @returns the created mesh
  49702. */
  49703. SolidParticleSystem.prototype.buildMesh = function () {
  49704. if (this.nbParticles === 0) {
  49705. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49706. this.addShape(triangle, 1);
  49707. triangle.dispose();
  49708. }
  49709. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49710. this._positions32 = new Float32Array(this._positions);
  49711. this._uvs32 = new Float32Array(this._uvs);
  49712. this._colors32 = new Float32Array(this._colors);
  49713. if (this.recomputeNormals) {
  49714. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49715. }
  49716. this._normals32 = new Float32Array(this._normals);
  49717. this._fixedNormal32 = new Float32Array(this._normals);
  49718. if (this._mustUnrotateFixedNormals) {
  49719. this._unrotateFixedNormals();
  49720. }
  49721. var vertexData = new BABYLON.VertexData();
  49722. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49723. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49724. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49725. if (this._uvs32) {
  49726. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49727. ;
  49728. }
  49729. if (this._colors32) {
  49730. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49731. }
  49732. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49733. vertexData.applyToMesh(mesh, this._updatable);
  49734. this.mesh = mesh;
  49735. this.mesh.isPickable = this._pickable;
  49736. // free memory
  49737. if (!this._depthSort) {
  49738. this._indices = null;
  49739. }
  49740. this._positions = null;
  49741. this._normals = null;
  49742. this._uvs = null;
  49743. this._colors = null;
  49744. if (!this._updatable) {
  49745. this.particles.length = 0;
  49746. }
  49747. return mesh;
  49748. };
  49749. /**
  49750. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49751. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49752. * Thus the particles generated from `digest()` have their property `position` set yet.
  49753. * @param mesh ( Mesh ) is the mesh to be digested
  49754. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49755. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49756. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49757. * @returns the current SPS
  49758. */
  49759. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49760. var size = (options && options.facetNb) || 1;
  49761. var number = (options && options.number) || 0;
  49762. var delta = (options && options.delta) || 0;
  49763. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49764. var meshInd = mesh.getIndices();
  49765. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49766. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49767. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49768. var f = 0; // facet counter
  49769. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49770. // compute size from number
  49771. if (number) {
  49772. number = (number > totalFacets) ? totalFacets : number;
  49773. size = Math.round(totalFacets / number);
  49774. delta = 0;
  49775. }
  49776. else {
  49777. size = (size > totalFacets) ? totalFacets : size;
  49778. }
  49779. var facetPos = []; // submesh positions
  49780. var facetInd = []; // submesh indices
  49781. var facetUV = []; // submesh UV
  49782. var facetCol = []; // submesh colors
  49783. var barycenter = BABYLON.Tmp.Vector3[0];
  49784. var sizeO = size;
  49785. while (f < totalFacets) {
  49786. size = sizeO + Math.floor((1 + delta) * Math.random());
  49787. if (f > totalFacets - size) {
  49788. size = totalFacets - f;
  49789. }
  49790. // reset temp arrays
  49791. facetPos.length = 0;
  49792. facetInd.length = 0;
  49793. facetUV.length = 0;
  49794. facetCol.length = 0;
  49795. // iterate over "size" facets
  49796. var fi = 0;
  49797. for (var j = f * 3; j < (f + size) * 3; j++) {
  49798. facetInd.push(fi);
  49799. var i = meshInd[j];
  49800. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49801. if (meshUV) {
  49802. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49803. }
  49804. if (meshCol) {
  49805. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49806. }
  49807. fi++;
  49808. }
  49809. // create a model shape for each single particle
  49810. var idx = this.nbParticles;
  49811. var shape = this._posToShape(facetPos);
  49812. var shapeUV = this._uvsToShapeUV(facetUV);
  49813. // compute the barycenter of the shape
  49814. var v;
  49815. for (v = 0; v < shape.length; v++) {
  49816. barycenter.addInPlace(shape[v]);
  49817. }
  49818. barycenter.scaleInPlace(1 / shape.length);
  49819. // shift the shape from its barycenter to the origin
  49820. for (v = 0; v < shape.length; v++) {
  49821. shape[v].subtractInPlace(barycenter);
  49822. }
  49823. var bInfo;
  49824. if (this._particlesIntersect) {
  49825. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49826. }
  49827. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  49828. // add the particle in the SPS
  49829. var currentPos = this._positions.length;
  49830. var currentInd = this._indices.length;
  49831. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49832. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  49833. // initialize the particle position
  49834. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49835. this._index += shape.length;
  49836. idx++;
  49837. this.nbParticles++;
  49838. this._shapeCounter++;
  49839. f += size;
  49840. }
  49841. return this;
  49842. };
  49843. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  49844. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  49845. var index = 0;
  49846. var idx = 0;
  49847. for (var p = 0; p < this.particles.length; p++) {
  49848. this._particle = this.particles[p];
  49849. this._shape = this._particle._model._shape;
  49850. if (this._particle.rotationQuaternion) {
  49851. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49852. }
  49853. else {
  49854. this._yaw = this._particle.rotation.y;
  49855. this._pitch = this._particle.rotation.x;
  49856. this._roll = this._particle.rotation.z;
  49857. this._quaternionRotationYPR();
  49858. }
  49859. this._quaternionToRotationMatrix();
  49860. this._rotMatrix.invertToRef(this._invertMatrix);
  49861. for (var pt = 0; pt < this._shape.length; pt++) {
  49862. idx = index + pt * 3;
  49863. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  49864. this._fixedNormal32[idx] = this._normal.x;
  49865. this._fixedNormal32[idx + 1] = this._normal.y;
  49866. this._fixedNormal32[idx + 2] = this._normal.z;
  49867. }
  49868. index = idx + 3;
  49869. }
  49870. };
  49871. //reset copy
  49872. SolidParticleSystem.prototype._resetCopy = function () {
  49873. this._copy.position.x = 0;
  49874. this._copy.position.y = 0;
  49875. this._copy.position.z = 0;
  49876. this._copy.rotation.x = 0;
  49877. this._copy.rotation.y = 0;
  49878. this._copy.rotation.z = 0;
  49879. this._copy.rotationQuaternion = null;
  49880. this._copy.scaling.x = 1.0;
  49881. this._copy.scaling.y = 1.0;
  49882. this._copy.scaling.z = 1.0;
  49883. this._copy.uvs.x = 0;
  49884. this._copy.uvs.y = 0;
  49885. this._copy.uvs.z = 1.0;
  49886. this._copy.uvs.w = 1.0;
  49887. this._copy.color = null;
  49888. };
  49889. // _meshBuilder : inserts the shape model in the global SPS mesh
  49890. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49891. var i;
  49892. var u = 0;
  49893. var c = 0;
  49894. var n = 0;
  49895. this._resetCopy();
  49896. if (options && options.positionFunction) {
  49897. options.positionFunction(this._copy, idx, idxInShape);
  49898. this._mustUnrotateFixedNormals = true;
  49899. }
  49900. if (this._copy.rotationQuaternion) {
  49901. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49902. }
  49903. else {
  49904. this._yaw = this._copy.rotation.y;
  49905. this._pitch = this._copy.rotation.x;
  49906. this._roll = this._copy.rotation.z;
  49907. this._quaternionRotationYPR();
  49908. }
  49909. this._quaternionToRotationMatrix();
  49910. for (i = 0; i < shape.length; i++) {
  49911. this._vertex.x = shape[i].x;
  49912. this._vertex.y = shape[i].y;
  49913. this._vertex.z = shape[i].z;
  49914. if (options && options.vertexFunction) {
  49915. options.vertexFunction(this._copy, this._vertex, i);
  49916. }
  49917. this._vertex.x *= this._copy.scaling.x;
  49918. this._vertex.y *= this._copy.scaling.y;
  49919. this._vertex.z *= this._copy.scaling.z;
  49920. this._vertex.x += this._copy.pivot.x;
  49921. this._vertex.y += this._copy.pivot.y;
  49922. this._vertex.z += this._copy.pivot.z;
  49923. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49924. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49925. if (meshUV) {
  49926. 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);
  49927. u += 2;
  49928. }
  49929. if (this._copy.color) {
  49930. this._color = this._copy.color;
  49931. }
  49932. else if (meshCol && meshCol[c] !== undefined) {
  49933. this._color.r = meshCol[c];
  49934. this._color.g = meshCol[c + 1];
  49935. this._color.b = meshCol[c + 2];
  49936. this._color.a = meshCol[c + 3];
  49937. }
  49938. else {
  49939. this._color.r = 1.0;
  49940. this._color.g = 1.0;
  49941. this._color.b = 1.0;
  49942. this._color.a = 1.0;
  49943. }
  49944. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49945. c += 4;
  49946. if (!this.recomputeNormals && meshNor) {
  49947. this._normal.x = meshNor[n];
  49948. this._normal.y = meshNor[n + 1];
  49949. this._normal.z = meshNor[n + 2];
  49950. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  49951. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49952. n += 3;
  49953. }
  49954. }
  49955. for (i = 0; i < meshInd.length; i++) {
  49956. var current_ind = p + meshInd[i];
  49957. indices.push(current_ind);
  49958. if (current_ind > 65535) {
  49959. this._needs32Bits = true;
  49960. }
  49961. }
  49962. if (this._pickable) {
  49963. var nbfaces = meshInd.length / 3;
  49964. for (i = 0; i < nbfaces; i++) {
  49965. this.pickedParticles.push({ idx: idx, faceId: i });
  49966. }
  49967. }
  49968. if (this._depthSort) {
  49969. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  49970. }
  49971. return this._copy;
  49972. };
  49973. // returns a shape array from positions array
  49974. SolidParticleSystem.prototype._posToShape = function (positions) {
  49975. var shape = [];
  49976. for (var i = 0; i < positions.length; i += 3) {
  49977. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49978. }
  49979. return shape;
  49980. };
  49981. // returns a shapeUV array from a Vector4 uvs
  49982. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49983. var shapeUV = [];
  49984. if (uvs) {
  49985. for (var i = 0; i < uvs.length; i++)
  49986. shapeUV.push(uvs[i]);
  49987. }
  49988. return shapeUV;
  49989. };
  49990. // adds a new particle object in the particles array
  49991. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  49992. if (bInfo === void 0) { bInfo = null; }
  49993. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  49994. this.particles.push(sp);
  49995. return sp;
  49996. };
  49997. /**
  49998. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49999. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50000. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  50001. * @param nb (positive integer) the number of particles to be created from this model
  50002. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  50003. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  50004. * @returns the number of shapes in the system
  50005. */
  50006. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50007. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50008. var meshInd = mesh.getIndices();
  50009. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50010. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50011. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50012. var bbInfo;
  50013. if (this._particlesIntersect) {
  50014. bbInfo = mesh.getBoundingInfo();
  50015. }
  50016. var shape = this._posToShape(meshPos);
  50017. var shapeUV = this._uvsToShapeUV(meshUV);
  50018. var posfunc = options ? options.positionFunction : null;
  50019. var vtxfunc = options ? options.vertexFunction : null;
  50020. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  50021. // particles
  50022. var sp;
  50023. var currentCopy;
  50024. var idx = this.nbParticles;
  50025. for (var i = 0; i < nb; i++) {
  50026. var currentPos = this._positions.length;
  50027. var currentInd = this._indices.length;
  50028. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50029. if (this._updatable) {
  50030. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  50031. sp.position.copyFrom(currentCopy.position);
  50032. sp.rotation.copyFrom(currentCopy.rotation);
  50033. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  50034. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  50035. }
  50036. if (currentCopy.color && sp.color) {
  50037. sp.color.copyFrom(currentCopy.color);
  50038. }
  50039. sp.scaling.copyFrom(currentCopy.scaling);
  50040. sp.uvs.copyFrom(currentCopy.uvs);
  50041. }
  50042. this._index += shape.length;
  50043. idx++;
  50044. }
  50045. this.nbParticles += nb;
  50046. this._shapeCounter++;
  50047. return this._shapeCounter - 1;
  50048. };
  50049. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50050. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50051. this._resetCopy();
  50052. if (particle._model._positionFunction) {
  50053. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50054. }
  50055. if (this._copy.rotationQuaternion) {
  50056. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50057. }
  50058. else {
  50059. this._yaw = this._copy.rotation.y;
  50060. this._pitch = this._copy.rotation.x;
  50061. this._roll = this._copy.rotation.z;
  50062. this._quaternionRotationYPR();
  50063. }
  50064. this._quaternionToRotationMatrix();
  50065. this._shape = particle._model._shape;
  50066. for (var pt = 0; pt < this._shape.length; pt++) {
  50067. this._vertex.x = this._shape[pt].x;
  50068. this._vertex.y = this._shape[pt].y;
  50069. this._vertex.z = this._shape[pt].z;
  50070. if (particle._model._vertexFunction) {
  50071. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50072. }
  50073. this._vertex.x *= this._copy.scaling.x;
  50074. this._vertex.y *= this._copy.scaling.y;
  50075. this._vertex.z *= this._copy.scaling.z;
  50076. this._vertex.x += this._copy.pivot.x;
  50077. this._vertex.y += this._copy.pivot.y;
  50078. this._vertex.z += this._copy.pivot.z;
  50079. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50080. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50081. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50082. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50083. }
  50084. particle.position.x = 0.0;
  50085. particle.position.y = 0.0;
  50086. particle.position.z = 0.0;
  50087. particle.rotation.x = 0.0;
  50088. particle.rotation.y = 0.0;
  50089. particle.rotation.z = 0.0;
  50090. particle.rotationQuaternion = null;
  50091. particle.scaling.x = 1.0;
  50092. particle.scaling.y = 1.0;
  50093. particle.scaling.z = 1.0;
  50094. };
  50095. /**
  50096. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50097. * @returns the SPS.
  50098. */
  50099. SolidParticleSystem.prototype.rebuildMesh = function () {
  50100. for (var p = 0; p < this.particles.length; p++) {
  50101. this._rebuildParticle(this.particles[p]);
  50102. }
  50103. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50104. return this;
  50105. };
  50106. /**
  50107. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50108. * This method calls `updateParticle()` for each particle of the SPS.
  50109. * For an animated SPS, it is usually called within the render loop.
  50110. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50111. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50112. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50113. * @returns the SPS.
  50114. */
  50115. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50116. if (start === void 0) { start = 0; }
  50117. if (end === void 0) { end = this.nbParticles - 1; }
  50118. if (update === void 0) { update = true; }
  50119. if (!this._updatable) {
  50120. return this;
  50121. }
  50122. // custom beforeUpdate
  50123. this.beforeUpdateParticles(start, end, update);
  50124. this._cam_axisX.x = 1.0;
  50125. this._cam_axisX.y = 0.0;
  50126. this._cam_axisX.z = 0.0;
  50127. this._cam_axisY.x = 0.0;
  50128. this._cam_axisY.y = 1.0;
  50129. this._cam_axisY.z = 0.0;
  50130. this._cam_axisZ.x = 0.0;
  50131. this._cam_axisZ.y = 0.0;
  50132. this._cam_axisZ.z = 1.0;
  50133. // cases when the World Matrix is to be computed first
  50134. if (this.billboard || this._depthSort) {
  50135. this.mesh.computeWorldMatrix(true);
  50136. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  50137. }
  50138. // if the particles will always face the camera
  50139. if (this.billboard) {
  50140. // compute the camera position and un-rotate it by the current mesh rotation
  50141. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  50142. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50143. this._cam_axisZ.normalize();
  50144. // same for camera up vector extracted from the cam view matrix
  50145. var view = this._camera.getViewMatrix(true);
  50146. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  50147. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50148. this._cam_axisY.normalize();
  50149. this._cam_axisX.normalize();
  50150. }
  50151. // if depthSort, compute the camera global position in the mesh local system
  50152. if (this._depthSort) {
  50153. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  50154. }
  50155. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50156. var idx = 0; // current position index in the global array positions32
  50157. var index = 0; // position start index in the global array positions32 of the current particle
  50158. var colidx = 0; // current color index in the global array colors32
  50159. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50160. var uvidx = 0; // current uv index in the global array uvs32
  50161. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50162. var pt = 0; // current index in the particle model shape
  50163. if (this.mesh.isFacetDataEnabled) {
  50164. this._computeBoundingBox = true;
  50165. }
  50166. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  50167. if (this._computeBoundingBox) {
  50168. if (start == 0 && end == this.nbParticles - 1) {
  50169. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50170. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50171. }
  50172. else {
  50173. if (this.mesh._boundingInfo) {
  50174. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  50175. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  50176. }
  50177. }
  50178. }
  50179. // particle loop
  50180. index = this.particles[start]._pos;
  50181. var vpos = (index / 3) | 0;
  50182. colorIndex = vpos * 4;
  50183. uvIndex = vpos * 2;
  50184. for (var p = start; p <= end; p++) {
  50185. this._particle = this.particles[p];
  50186. this._shape = this._particle._model._shape;
  50187. this._shapeUV = this._particle._model._shapeUV;
  50188. // call to custom user function to update the particle properties
  50189. this.updateParticle(this._particle);
  50190. // camera-particle distance for depth sorting
  50191. if (this._depthSort && this._depthSortParticles) {
  50192. var dsp = this.depthSortedParticles[p];
  50193. dsp.ind = this._particle._ind;
  50194. dsp.indicesLength = this._particle._model._indicesLength;
  50195. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  50196. }
  50197. // skip the computations for inactive or already invisible particles
  50198. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  50199. // increment indexes for the next particle
  50200. pt = this._shape.length;
  50201. index += pt * 3;
  50202. colorIndex += pt * 4;
  50203. uvIndex += pt * 2;
  50204. continue;
  50205. }
  50206. if (this._particle.isVisible) {
  50207. this._particle._stillInvisible = false; // un-mark permanent invisibility
  50208. // particle rotation matrix
  50209. if (this.billboard) {
  50210. this._particle.rotation.x = 0.0;
  50211. this._particle.rotation.y = 0.0;
  50212. }
  50213. if (this._computeParticleRotation || this.billboard) {
  50214. if (this._particle.rotationQuaternion) {
  50215. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50216. }
  50217. else {
  50218. this._yaw = this._particle.rotation.y;
  50219. this._pitch = this._particle.rotation.x;
  50220. this._roll = this._particle.rotation.z;
  50221. this._quaternionRotationYPR();
  50222. }
  50223. this._quaternionToRotationMatrix();
  50224. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  50225. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  50226. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  50227. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  50228. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  50229. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  50230. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  50231. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  50232. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  50233. }
  50234. // particle vertex loop
  50235. for (pt = 0; pt < this._shape.length; pt++) {
  50236. idx = index + pt * 3;
  50237. colidx = colorIndex + pt * 4;
  50238. uvidx = uvIndex + pt * 2;
  50239. this._vertex.x = this._shape[pt].x;
  50240. this._vertex.y = this._shape[pt].y;
  50241. this._vertex.z = this._shape[pt].z;
  50242. if (this._computeParticleVertex) {
  50243. this.updateParticleVertex(this._particle, this._vertex, pt);
  50244. }
  50245. // positions
  50246. this._vertex.x *= this._particle.scaling.x;
  50247. this._vertex.y *= this._particle.scaling.y;
  50248. this._vertex.z *= this._particle.scaling.z;
  50249. this._vertex.x += this._particle.pivot.x;
  50250. this._vertex.y += this._particle.pivot.y;
  50251. this._vertex.z += this._particle.pivot.z;
  50252. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50253. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50254. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50255. 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;
  50256. 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;
  50257. 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;
  50258. if (this._computeBoundingBox) {
  50259. if (this._positions32[idx] < this._minimum.x) {
  50260. this._minimum.x = this._positions32[idx];
  50261. }
  50262. if (this._positions32[idx] > this._maximum.x) {
  50263. this._maximum.x = this._positions32[idx];
  50264. }
  50265. if (this._positions32[idx + 1] < this._minimum.y) {
  50266. this._minimum.y = this._positions32[idx + 1];
  50267. }
  50268. if (this._positions32[idx + 1] > this._maximum.y) {
  50269. this._maximum.y = this._positions32[idx + 1];
  50270. }
  50271. if (this._positions32[idx + 2] < this._minimum.z) {
  50272. this._minimum.z = this._positions32[idx + 2];
  50273. }
  50274. if (this._positions32[idx + 2] > this._maximum.z) {
  50275. this._maximum.z = this._positions32[idx + 2];
  50276. }
  50277. }
  50278. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50279. if (!this._computeParticleVertex) {
  50280. this._normal.x = this._fixedNormal32[idx];
  50281. this._normal.y = this._fixedNormal32[idx + 1];
  50282. this._normal.z = this._fixedNormal32[idx + 2];
  50283. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  50284. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  50285. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  50286. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50287. 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;
  50288. 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;
  50289. }
  50290. if (this._computeParticleColor && this._particle.color) {
  50291. this._colors32[colidx] = this._particle.color.r;
  50292. this._colors32[colidx + 1] = this._particle.color.g;
  50293. this._colors32[colidx + 2] = this._particle.color.b;
  50294. this._colors32[colidx + 3] = this._particle.color.a;
  50295. }
  50296. if (this._computeParticleTexture) {
  50297. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50298. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50299. }
  50300. }
  50301. }
  50302. else {
  50303. this._particle._stillInvisible = true; // mark the particle as invisible
  50304. for (pt = 0; pt < this._shape.length; pt++) {
  50305. idx = index + pt * 3;
  50306. colidx = colorIndex + pt * 4;
  50307. uvidx = uvIndex + pt * 2;
  50308. this._positions32[idx] = 0.0;
  50309. this._positions32[idx + 1] = 0.0;
  50310. this._positions32[idx + 2] = 0.0;
  50311. this._normals32[idx] = 0.0;
  50312. this._normals32[idx + 1] = 0.0;
  50313. this._normals32[idx + 2] = 0.0;
  50314. if (this._computeParticleColor && this._particle.color) {
  50315. this._colors32[colidx] = this._particle.color.r;
  50316. this._colors32[colidx + 1] = this._particle.color.g;
  50317. this._colors32[colidx + 2] = this._particle.color.b;
  50318. this._colors32[colidx + 3] = this._particle.color.a;
  50319. }
  50320. if (this._computeParticleTexture) {
  50321. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50322. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50323. }
  50324. }
  50325. }
  50326. // if the particle intersections must be computed : update the bbInfo
  50327. if (this._particlesIntersect) {
  50328. var bInfo = this._particle._boundingInfo;
  50329. var bBox = bInfo.boundingBox;
  50330. var bSphere = bInfo.boundingSphere;
  50331. if (!this._bSphereOnly) {
  50332. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50333. for (var b = 0; b < bBox.vectors.length; b++) {
  50334. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50335. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50336. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50337. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  50338. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  50339. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  50340. 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;
  50341. 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;
  50342. 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;
  50343. }
  50344. bBox._update(this.mesh._worldMatrix);
  50345. }
  50346. // place and scale the particle bouding sphere in the SPS local system, then update it
  50347. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50348. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50349. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50350. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50351. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50352. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50353. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50354. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50355. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50356. 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));
  50357. bSphere._update(this.mesh._worldMatrix);
  50358. }
  50359. // increment indexes for the next particle
  50360. index = idx + 3;
  50361. colorIndex = colidx + 4;
  50362. uvIndex = uvidx + 2;
  50363. }
  50364. // if the VBO must be updated
  50365. if (update) {
  50366. if (this._computeParticleColor) {
  50367. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50368. }
  50369. if (this._computeParticleTexture) {
  50370. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50371. }
  50372. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50373. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50374. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50375. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50376. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50377. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  50378. for (var i = 0; i < this._normals32.length; i++) {
  50379. this._fixedNormal32[i] = this._normals32[i];
  50380. }
  50381. }
  50382. if (!this.mesh.areNormalsFrozen) {
  50383. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50384. }
  50385. }
  50386. if (this._depthSort && this._depthSortParticles) {
  50387. this.depthSortedParticles.sort(this._depthSortFunction);
  50388. var dspl = this.depthSortedParticles.length;
  50389. var sorted = 0;
  50390. var lind = 0;
  50391. var sind = 0;
  50392. var sid = 0;
  50393. for (sorted = 0; sorted < dspl; sorted++) {
  50394. lind = this.depthSortedParticles[sorted].indicesLength;
  50395. sind = this.depthSortedParticles[sorted].ind;
  50396. for (var i = 0; i < lind; i++) {
  50397. this._indices32[sid] = this._indices[sind + i];
  50398. sid++;
  50399. }
  50400. }
  50401. this.mesh.updateIndices(this._indices32);
  50402. }
  50403. }
  50404. if (this._computeBoundingBox) {
  50405. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50406. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50407. }
  50408. this.afterUpdateParticles(start, end, update);
  50409. return this;
  50410. };
  50411. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50412. this._halfroll = this._roll * 0.5;
  50413. this._halfpitch = this._pitch * 0.5;
  50414. this._halfyaw = this._yaw * 0.5;
  50415. this._sinRoll = Math.sin(this._halfroll);
  50416. this._cosRoll = Math.cos(this._halfroll);
  50417. this._sinPitch = Math.sin(this._halfpitch);
  50418. this._cosPitch = Math.cos(this._halfpitch);
  50419. this._sinYaw = Math.sin(this._halfyaw);
  50420. this._cosYaw = Math.cos(this._halfyaw);
  50421. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  50422. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  50423. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  50424. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  50425. };
  50426. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50427. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50428. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50429. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50430. this._rotMatrix.m[3] = 0;
  50431. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50432. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50433. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50434. this._rotMatrix.m[7] = 0;
  50435. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50436. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50437. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50438. this._rotMatrix.m[11] = 0;
  50439. this._rotMatrix.m[12] = 0;
  50440. this._rotMatrix.m[13] = 0;
  50441. this._rotMatrix.m[14] = 0;
  50442. this._rotMatrix.m[15] = 1.0;
  50443. };
  50444. /**
  50445. * Disposes the SPS.
  50446. */
  50447. SolidParticleSystem.prototype.dispose = function () {
  50448. this.mesh.dispose();
  50449. this.vars = null;
  50450. // drop references to internal big arrays for the GC
  50451. this._positions = null;
  50452. this._indices = null;
  50453. this._normals = null;
  50454. this._uvs = null;
  50455. this._colors = null;
  50456. this._indices32 = null;
  50457. this._positions32 = null;
  50458. this._normals32 = null;
  50459. this._fixedNormal32 = null;
  50460. this._uvs32 = null;
  50461. this._colors32 = null;
  50462. this.pickedParticles = null;
  50463. };
  50464. /**
  50465. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50466. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50467. * @returns the SPS.
  50468. */
  50469. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50470. if (!this._isVisibilityBoxLocked) {
  50471. this.mesh.refreshBoundingInfo();
  50472. }
  50473. return this;
  50474. };
  50475. /**
  50476. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50477. * @param size the size (float) of the visibility box
  50478. * note : this doesn't lock the SPS mesh bounding box.
  50479. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50480. */
  50481. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50482. var vis = size / 2;
  50483. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50484. };
  50485. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50486. /**
  50487. * Gets whether the SPS as always visible or not
  50488. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50489. */
  50490. get: function () {
  50491. return this._alwaysVisible;
  50492. },
  50493. /**
  50494. * Sets the SPS as always visible or not
  50495. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50496. */
  50497. set: function (val) {
  50498. this._alwaysVisible = val;
  50499. this.mesh.alwaysSelectAsActiveMesh = val;
  50500. },
  50501. enumerable: true,
  50502. configurable: true
  50503. });
  50504. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50505. /**
  50506. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50507. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50508. */
  50509. get: function () {
  50510. return this._isVisibilityBoxLocked;
  50511. },
  50512. /**
  50513. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50514. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50515. */
  50516. set: function (val) {
  50517. this._isVisibilityBoxLocked = val;
  50518. var boundingInfo = this.mesh.getBoundingInfo();
  50519. boundingInfo.isLocked = val;
  50520. },
  50521. enumerable: true,
  50522. configurable: true
  50523. });
  50524. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50525. /**
  50526. * Gets if `setParticles()` computes the particle rotations or not.
  50527. * Default value : true. The SPS is faster when it's set to false.
  50528. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50529. */
  50530. get: function () {
  50531. return this._computeParticleRotation;
  50532. },
  50533. /**
  50534. * Tells to `setParticles()` to compute the particle rotations or not.
  50535. * Default value : true. The SPS is faster when it's set to false.
  50536. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50537. */
  50538. set: function (val) {
  50539. this._computeParticleRotation = val;
  50540. },
  50541. enumerable: true,
  50542. configurable: true
  50543. });
  50544. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50545. /**
  50546. * Gets if `setParticles()` computes the particle colors or not.
  50547. * Default value : true. The SPS is faster when it's set to false.
  50548. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50549. */
  50550. get: function () {
  50551. return this._computeParticleColor;
  50552. },
  50553. /**
  50554. * Tells to `setParticles()` to compute the particle colors or not.
  50555. * Default value : true. The SPS is faster when it's set to false.
  50556. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50557. */
  50558. set: function (val) {
  50559. this._computeParticleColor = val;
  50560. },
  50561. enumerable: true,
  50562. configurable: true
  50563. });
  50564. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50565. /**
  50566. * Gets if `setParticles()` computes the particle textures or not.
  50567. * Default value : true. The SPS is faster when it's set to false.
  50568. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50569. */
  50570. get: function () {
  50571. return this._computeParticleTexture;
  50572. },
  50573. set: function (val) {
  50574. this._computeParticleTexture = val;
  50575. },
  50576. enumerable: true,
  50577. configurable: true
  50578. });
  50579. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50580. /**
  50581. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  50582. * Default value : false. The SPS is faster when it's set to false.
  50583. * Note : the particle custom vertex positions aren't stored values.
  50584. */
  50585. get: function () {
  50586. return this._computeParticleVertex;
  50587. },
  50588. /**
  50589. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50590. * Default value : false. The SPS is faster when it's set to false.
  50591. * Note : the particle custom vertex positions aren't stored values.
  50592. */
  50593. set: function (val) {
  50594. this._computeParticleVertex = val;
  50595. },
  50596. enumerable: true,
  50597. configurable: true
  50598. });
  50599. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50600. /**
  50601. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  50602. */
  50603. get: function () {
  50604. return this._computeBoundingBox;
  50605. },
  50606. /**
  50607. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50608. */
  50609. set: function (val) {
  50610. this._computeBoundingBox = val;
  50611. },
  50612. enumerable: true,
  50613. configurable: true
  50614. });
  50615. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  50616. /**
  50617. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  50618. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50619. * Default : `true`
  50620. */
  50621. get: function () {
  50622. return this._depthSortParticles;
  50623. },
  50624. /**
  50625. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  50626. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50627. * Default : `true`
  50628. */
  50629. set: function (val) {
  50630. this._depthSortParticles = val;
  50631. },
  50632. enumerable: true,
  50633. configurable: true
  50634. });
  50635. // =======================================================================
  50636. // Particle behavior logic
  50637. // these following methods may be overwritten by the user to fit his needs
  50638. /**
  50639. * This function does nothing. It may be overwritten to set all the particle first values.
  50640. * The SPS doesn't call this function, you may have to call it by your own.
  50641. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50642. */
  50643. SolidParticleSystem.prototype.initParticles = function () {
  50644. };
  50645. /**
  50646. * This function does nothing. It may be overwritten to recycle a particle.
  50647. * The SPS doesn't call this function, you may have to call it by your own.
  50648. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50649. * @param particle The particle to recycle
  50650. * @returns the recycled particle
  50651. */
  50652. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50653. return particle;
  50654. };
  50655. /**
  50656. * Updates a particle : this function should be overwritten by the user.
  50657. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50658. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50659. * @example : just set a particle position or velocity and recycle conditions
  50660. * @param particle The particle to update
  50661. * @returns the updated particle
  50662. */
  50663. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50664. return particle;
  50665. };
  50666. /**
  50667. * Updates a vertex of a particle : it can be overwritten by the user.
  50668. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50669. * @param particle the current particle
  50670. * @param vertex the current index of the current particle
  50671. * @param pt the index of the current vertex in the particle shape
  50672. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50673. * @example : just set a vertex particle position
  50674. * @returns the updated vertex
  50675. */
  50676. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50677. return vertex;
  50678. };
  50679. /**
  50680. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50681. * This does nothing and may be overwritten by the user.
  50682. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50683. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50684. * @param update the boolean update value actually passed to setParticles()
  50685. */
  50686. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50687. };
  50688. /**
  50689. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50690. * This will be passed three parameters.
  50691. * This does nothing and may be overwritten by the user.
  50692. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50693. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50694. * @param update the boolean update value actually passed to setParticles()
  50695. */
  50696. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50697. };
  50698. return SolidParticleSystem;
  50699. }());
  50700. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50701. })(BABYLON || (BABYLON = {}));
  50702. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50703. var BABYLON;
  50704. (function (BABYLON) {
  50705. var ShaderMaterial = /** @class */ (function (_super) {
  50706. __extends(ShaderMaterial, _super);
  50707. function ShaderMaterial(name, scene, shaderPath, options) {
  50708. var _this = _super.call(this, name, scene) || this;
  50709. _this._textures = {};
  50710. _this._textureArrays = {};
  50711. _this._floats = {};
  50712. _this._ints = {};
  50713. _this._floatsArrays = {};
  50714. _this._colors3 = {};
  50715. _this._colors3Arrays = {};
  50716. _this._colors4 = {};
  50717. _this._vectors2 = {};
  50718. _this._vectors3 = {};
  50719. _this._vectors4 = {};
  50720. _this._matrices = {};
  50721. _this._matrices3x3 = {};
  50722. _this._matrices2x2 = {};
  50723. _this._vectors2Arrays = {};
  50724. _this._vectors3Arrays = {};
  50725. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50726. _this._shaderPath = shaderPath;
  50727. options.needAlphaBlending = options.needAlphaBlending || false;
  50728. options.needAlphaTesting = options.needAlphaTesting || false;
  50729. options.attributes = options.attributes || ["position", "normal", "uv"];
  50730. options.uniforms = options.uniforms || ["worldViewProjection"];
  50731. options.uniformBuffers = options.uniformBuffers || [];
  50732. options.samplers = options.samplers || [];
  50733. options.defines = options.defines || [];
  50734. _this._options = options;
  50735. return _this;
  50736. }
  50737. ShaderMaterial.prototype.getClassName = function () {
  50738. return "ShaderMaterial";
  50739. };
  50740. ShaderMaterial.prototype.needAlphaBlending = function () {
  50741. return this._options.needAlphaBlending;
  50742. };
  50743. ShaderMaterial.prototype.needAlphaTesting = function () {
  50744. return this._options.needAlphaTesting;
  50745. };
  50746. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50747. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50748. this._options.uniforms.push(uniformName);
  50749. }
  50750. };
  50751. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50752. if (this._options.samplers.indexOf(name) === -1) {
  50753. this._options.samplers.push(name);
  50754. }
  50755. this._textures[name] = texture;
  50756. return this;
  50757. };
  50758. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50759. if (this._options.samplers.indexOf(name) === -1) {
  50760. this._options.samplers.push(name);
  50761. }
  50762. this._checkUniform(name);
  50763. this._textureArrays[name] = textures;
  50764. return this;
  50765. };
  50766. ShaderMaterial.prototype.setFloat = function (name, value) {
  50767. this._checkUniform(name);
  50768. this._floats[name] = value;
  50769. return this;
  50770. };
  50771. ShaderMaterial.prototype.setInt = function (name, value) {
  50772. this._checkUniform(name);
  50773. this._ints[name] = value;
  50774. return this;
  50775. };
  50776. ShaderMaterial.prototype.setFloats = function (name, value) {
  50777. this._checkUniform(name);
  50778. this._floatsArrays[name] = value;
  50779. return this;
  50780. };
  50781. ShaderMaterial.prototype.setColor3 = function (name, value) {
  50782. this._checkUniform(name);
  50783. this._colors3[name] = value;
  50784. return this;
  50785. };
  50786. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  50787. this._checkUniform(name);
  50788. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  50789. color.toArray(arr, arr.length);
  50790. return arr;
  50791. }, []);
  50792. return this;
  50793. };
  50794. ShaderMaterial.prototype.setColor4 = function (name, value) {
  50795. this._checkUniform(name);
  50796. this._colors4[name] = value;
  50797. return this;
  50798. };
  50799. ShaderMaterial.prototype.setVector2 = function (name, value) {
  50800. this._checkUniform(name);
  50801. this._vectors2[name] = value;
  50802. return this;
  50803. };
  50804. ShaderMaterial.prototype.setVector3 = function (name, value) {
  50805. this._checkUniform(name);
  50806. this._vectors3[name] = value;
  50807. return this;
  50808. };
  50809. ShaderMaterial.prototype.setVector4 = function (name, value) {
  50810. this._checkUniform(name);
  50811. this._vectors4[name] = value;
  50812. return this;
  50813. };
  50814. ShaderMaterial.prototype.setMatrix = function (name, value) {
  50815. this._checkUniform(name);
  50816. this._matrices[name] = value;
  50817. return this;
  50818. };
  50819. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  50820. this._checkUniform(name);
  50821. this._matrices3x3[name] = value;
  50822. return this;
  50823. };
  50824. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  50825. this._checkUniform(name);
  50826. this._matrices2x2[name] = value;
  50827. return this;
  50828. };
  50829. ShaderMaterial.prototype.setArray2 = function (name, value) {
  50830. this._checkUniform(name);
  50831. this._vectors2Arrays[name] = value;
  50832. return this;
  50833. };
  50834. ShaderMaterial.prototype.setArray3 = function (name, value) {
  50835. this._checkUniform(name);
  50836. this._vectors3Arrays[name] = value;
  50837. return this;
  50838. };
  50839. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  50840. if (!mesh) {
  50841. return true;
  50842. }
  50843. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  50844. return false;
  50845. }
  50846. return false;
  50847. };
  50848. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  50849. var scene = this.getScene();
  50850. var engine = scene.getEngine();
  50851. if (!this.checkReadyOnEveryCall) {
  50852. if (this._renderId === scene.getRenderId()) {
  50853. if (this._checkCache(scene, mesh, useInstances)) {
  50854. return true;
  50855. }
  50856. }
  50857. }
  50858. // Instances
  50859. var defines = [];
  50860. var attribs = [];
  50861. var fallbacks = new BABYLON.EffectFallbacks();
  50862. if (useInstances) {
  50863. defines.push("#define INSTANCES");
  50864. }
  50865. for (var index = 0; index < this._options.defines.length; index++) {
  50866. defines.push(this._options.defines[index]);
  50867. }
  50868. for (var index = 0; index < this._options.attributes.length; index++) {
  50869. attribs.push(this._options.attributes[index]);
  50870. }
  50871. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  50872. attribs.push(BABYLON.VertexBuffer.ColorKind);
  50873. defines.push("#define VERTEXCOLOR");
  50874. }
  50875. // Bones
  50876. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  50877. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50878. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50879. if (mesh.numBoneInfluencers > 4) {
  50880. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50881. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50882. }
  50883. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50884. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50885. fallbacks.addCPUSkinningFallback(0, mesh);
  50886. if (this._options.uniforms.indexOf("mBones") === -1) {
  50887. this._options.uniforms.push("mBones");
  50888. }
  50889. }
  50890. else {
  50891. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50892. }
  50893. // Textures
  50894. for (var name in this._textures) {
  50895. if (!this._textures[name].isReady()) {
  50896. return false;
  50897. }
  50898. }
  50899. // Alpha test
  50900. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  50901. defines.push("#define ALPHATEST");
  50902. }
  50903. var previousEffect = this._effect;
  50904. var join = defines.join("\n");
  50905. this._effect = engine.createEffect(this._shaderPath, {
  50906. attributes: attribs,
  50907. uniformsNames: this._options.uniforms,
  50908. uniformBuffersNames: this._options.uniformBuffers,
  50909. samplers: this._options.samplers,
  50910. defines: join,
  50911. fallbacks: fallbacks,
  50912. onCompiled: this.onCompiled,
  50913. onError: this.onError
  50914. }, engine);
  50915. if (!this._effect.isReady()) {
  50916. return false;
  50917. }
  50918. if (previousEffect !== this._effect) {
  50919. scene.resetCachedMaterial();
  50920. }
  50921. this._renderId = scene.getRenderId();
  50922. return true;
  50923. };
  50924. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  50925. var scene = this.getScene();
  50926. if (!this._effect) {
  50927. return;
  50928. }
  50929. if (this._options.uniforms.indexOf("world") !== -1) {
  50930. this._effect.setMatrix("world", world);
  50931. }
  50932. if (this._options.uniforms.indexOf("worldView") !== -1) {
  50933. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  50934. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  50935. }
  50936. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  50937. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  50938. }
  50939. };
  50940. ShaderMaterial.prototype.bind = function (world, mesh) {
  50941. // Std values
  50942. this.bindOnlyWorldMatrix(world);
  50943. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  50944. if (this._options.uniforms.indexOf("view") !== -1) {
  50945. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  50946. }
  50947. if (this._options.uniforms.indexOf("projection") !== -1) {
  50948. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  50949. }
  50950. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  50951. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  50952. }
  50953. // Bones
  50954. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  50955. var name;
  50956. // Texture
  50957. for (name in this._textures) {
  50958. this._effect.setTexture(name, this._textures[name]);
  50959. }
  50960. // Texture arrays
  50961. for (name in this._textureArrays) {
  50962. this._effect.setTextureArray(name, this._textureArrays[name]);
  50963. }
  50964. // Int
  50965. for (name in this._ints) {
  50966. this._effect.setInt(name, this._ints[name]);
  50967. }
  50968. // Float
  50969. for (name in this._floats) {
  50970. this._effect.setFloat(name, this._floats[name]);
  50971. }
  50972. // Floats
  50973. for (name in this._floatsArrays) {
  50974. this._effect.setArray(name, this._floatsArrays[name]);
  50975. }
  50976. // Color3
  50977. for (name in this._colors3) {
  50978. this._effect.setColor3(name, this._colors3[name]);
  50979. }
  50980. for (name in this._colors3Arrays) {
  50981. this._effect.setArray3(name, this._colors3Arrays[name]);
  50982. }
  50983. // Color4
  50984. for (name in this._colors4) {
  50985. var color = this._colors4[name];
  50986. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50987. }
  50988. // Vector2
  50989. for (name in this._vectors2) {
  50990. this._effect.setVector2(name, this._vectors2[name]);
  50991. }
  50992. // Vector3
  50993. for (name in this._vectors3) {
  50994. this._effect.setVector3(name, this._vectors3[name]);
  50995. }
  50996. // Vector4
  50997. for (name in this._vectors4) {
  50998. this._effect.setVector4(name, this._vectors4[name]);
  50999. }
  51000. // Matrix
  51001. for (name in this._matrices) {
  51002. this._effect.setMatrix(name, this._matrices[name]);
  51003. }
  51004. // Matrix 3x3
  51005. for (name in this._matrices3x3) {
  51006. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  51007. }
  51008. // Matrix 2x2
  51009. for (name in this._matrices2x2) {
  51010. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  51011. }
  51012. // Vector2Array
  51013. for (name in this._vectors2Arrays) {
  51014. this._effect.setArray2(name, this._vectors2Arrays[name]);
  51015. }
  51016. // Vector3Array
  51017. for (name in this._vectors3Arrays) {
  51018. this._effect.setArray3(name, this._vectors3Arrays[name]);
  51019. }
  51020. }
  51021. this._afterBind(mesh);
  51022. };
  51023. ShaderMaterial.prototype.getActiveTextures = function () {
  51024. var activeTextures = _super.prototype.getActiveTextures.call(this);
  51025. for (var name in this._textures) {
  51026. activeTextures.push(this._textures[name]);
  51027. }
  51028. for (var name in this._textureArrays) {
  51029. var array = this._textureArrays[name];
  51030. for (var index = 0; index < array.length; index++) {
  51031. activeTextures.push(array[index]);
  51032. }
  51033. }
  51034. return activeTextures;
  51035. };
  51036. ShaderMaterial.prototype.hasTexture = function (texture) {
  51037. if (_super.prototype.hasTexture.call(this, texture)) {
  51038. return true;
  51039. }
  51040. for (var name in this._textures) {
  51041. if (this._textures[name] === texture) {
  51042. return true;
  51043. }
  51044. }
  51045. for (var name in this._textureArrays) {
  51046. var array = this._textureArrays[name];
  51047. for (var index = 0; index < array.length; index++) {
  51048. if (array[index] === texture) {
  51049. return true;
  51050. }
  51051. }
  51052. }
  51053. return false;
  51054. };
  51055. ShaderMaterial.prototype.clone = function (name) {
  51056. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  51057. return newShaderMaterial;
  51058. };
  51059. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51060. if (forceDisposeTextures) {
  51061. var name;
  51062. for (name in this._textures) {
  51063. this._textures[name].dispose();
  51064. }
  51065. for (name in this._textureArrays) {
  51066. var array = this._textureArrays[name];
  51067. for (var index = 0; index < array.length; index++) {
  51068. array[index].dispose();
  51069. }
  51070. }
  51071. }
  51072. this._textures = {};
  51073. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51074. };
  51075. ShaderMaterial.prototype.serialize = function () {
  51076. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51077. serializationObject.customType = "BABYLON.ShaderMaterial";
  51078. serializationObject.options = this._options;
  51079. serializationObject.shaderPath = this._shaderPath;
  51080. var name;
  51081. // Texture
  51082. serializationObject.textures = {};
  51083. for (name in this._textures) {
  51084. serializationObject.textures[name] = this._textures[name].serialize();
  51085. }
  51086. // Texture arrays
  51087. serializationObject.textureArrays = {};
  51088. for (name in this._textureArrays) {
  51089. serializationObject.textureArrays[name] = [];
  51090. var array = this._textureArrays[name];
  51091. for (var index = 0; index < array.length; index++) {
  51092. serializationObject.textureArrays[name].push(array[index].serialize());
  51093. }
  51094. }
  51095. // Float
  51096. serializationObject.floats = {};
  51097. for (name in this._floats) {
  51098. serializationObject.floats[name] = this._floats[name];
  51099. }
  51100. // Float s
  51101. serializationObject.FloatArrays = {};
  51102. for (name in this._floatsArrays) {
  51103. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  51104. }
  51105. // Color3
  51106. serializationObject.colors3 = {};
  51107. for (name in this._colors3) {
  51108. serializationObject.colors3[name] = this._colors3[name].asArray();
  51109. }
  51110. // Color3 array
  51111. serializationObject.colors3Arrays = {};
  51112. for (name in this._colors3Arrays) {
  51113. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  51114. }
  51115. // Color4
  51116. serializationObject.colors4 = {};
  51117. for (name in this._colors4) {
  51118. serializationObject.colors4[name] = this._colors4[name].asArray();
  51119. }
  51120. // Vector2
  51121. serializationObject.vectors2 = {};
  51122. for (name in this._vectors2) {
  51123. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  51124. }
  51125. // Vector3
  51126. serializationObject.vectors3 = {};
  51127. for (name in this._vectors3) {
  51128. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  51129. }
  51130. // Vector4
  51131. serializationObject.vectors4 = {};
  51132. for (name in this._vectors4) {
  51133. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  51134. }
  51135. // Matrix
  51136. serializationObject.matrices = {};
  51137. for (name in this._matrices) {
  51138. serializationObject.matrices[name] = this._matrices[name].asArray();
  51139. }
  51140. // Matrix 3x3
  51141. serializationObject.matrices3x3 = {};
  51142. for (name in this._matrices3x3) {
  51143. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  51144. }
  51145. // Matrix 2x2
  51146. serializationObject.matrices2x2 = {};
  51147. for (name in this._matrices2x2) {
  51148. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  51149. }
  51150. // Vector2Array
  51151. serializationObject.vectors2Arrays = {};
  51152. for (name in this._vectors2Arrays) {
  51153. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  51154. }
  51155. // Vector3Array
  51156. serializationObject.vectors3Arrays = {};
  51157. for (name in this._vectors3Arrays) {
  51158. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  51159. }
  51160. return serializationObject;
  51161. };
  51162. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  51163. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  51164. var name;
  51165. // Texture
  51166. for (name in source.textures) {
  51167. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  51168. }
  51169. // Texture arrays
  51170. for (name in source.textureArrays) {
  51171. var array = source.textureArrays[name];
  51172. var textureArray = new Array();
  51173. for (var index = 0; index < array.length; index++) {
  51174. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  51175. }
  51176. material.setTextureArray(name, textureArray);
  51177. }
  51178. // Float
  51179. for (name in source.floats) {
  51180. material.setFloat(name, source.floats[name]);
  51181. }
  51182. // Float s
  51183. for (name in source.floatsArrays) {
  51184. material.setFloats(name, source.floatsArrays[name]);
  51185. }
  51186. // Color3
  51187. for (name in source.colors3) {
  51188. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  51189. }
  51190. // Color3 arrays
  51191. for (name in source.colors3Arrays) {
  51192. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  51193. if (i % 3 === 0) {
  51194. arr.push([num]);
  51195. }
  51196. else {
  51197. arr[arr.length - 1].push(num);
  51198. }
  51199. return arr;
  51200. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  51201. material.setColor3Array(name, colors);
  51202. }
  51203. // Color4
  51204. for (name in source.colors4) {
  51205. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  51206. }
  51207. // Vector2
  51208. for (name in source.vectors2) {
  51209. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  51210. }
  51211. // Vector3
  51212. for (name in source.vectors3) {
  51213. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  51214. }
  51215. // Vector4
  51216. for (name in source.vectors4) {
  51217. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  51218. }
  51219. // Matrix
  51220. for (name in source.matrices) {
  51221. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  51222. }
  51223. // Matrix 3x3
  51224. for (name in source.matrices3x3) {
  51225. material.setMatrix3x3(name, source.matrices3x3[name]);
  51226. }
  51227. // Matrix 2x2
  51228. for (name in source.matrices2x2) {
  51229. material.setMatrix2x2(name, source.matrices2x2[name]);
  51230. }
  51231. // Vector2Array
  51232. for (name in source.vectors2Arrays) {
  51233. material.setArray2(name, source.vectors2Arrays[name]);
  51234. }
  51235. // Vector3Array
  51236. for (name in source.vectors3Arrays) {
  51237. material.setArray3(name, source.vectors3Arrays[name]);
  51238. }
  51239. return material;
  51240. };
  51241. return ShaderMaterial;
  51242. }(BABYLON.Material));
  51243. BABYLON.ShaderMaterial = ShaderMaterial;
  51244. })(BABYLON || (BABYLON = {}));
  51245. //# sourceMappingURL=babylon.shaderMaterial.js.map
  51246. var BABYLON;
  51247. (function (BABYLON) {
  51248. var GroundMesh = /** @class */ (function (_super) {
  51249. __extends(GroundMesh, _super);
  51250. function GroundMesh(name, scene) {
  51251. var _this = _super.call(this, name, scene) || this;
  51252. _this.generateOctree = false;
  51253. return _this;
  51254. }
  51255. GroundMesh.prototype.getClassName = function () {
  51256. return "GroundMesh";
  51257. };
  51258. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  51259. get: function () {
  51260. return Math.min(this._subdivisionsX, this._subdivisionsY);
  51261. },
  51262. enumerable: true,
  51263. configurable: true
  51264. });
  51265. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  51266. get: function () {
  51267. return this._subdivisionsX;
  51268. },
  51269. enumerable: true,
  51270. configurable: true
  51271. });
  51272. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  51273. get: function () {
  51274. return this._subdivisionsY;
  51275. },
  51276. enumerable: true,
  51277. configurable: true
  51278. });
  51279. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  51280. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  51281. this._subdivisionsX = chunksCount;
  51282. this._subdivisionsY = chunksCount;
  51283. this.subdivide(chunksCount);
  51284. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  51285. };
  51286. /**
  51287. * Returns a height (y) value in the Worl system :
  51288. * the ground altitude at the coordinates (x, z) expressed in the World system.
  51289. * Returns the ground y position if (x, z) are outside the ground surface.
  51290. */
  51291. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  51292. var world = this.getWorldMatrix();
  51293. var invMat = BABYLON.Tmp.Matrix[5];
  51294. world.invertToRef(invMat);
  51295. var tmpVect = BABYLON.Tmp.Vector3[8];
  51296. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  51297. x = tmpVect.x;
  51298. z = tmpVect.z;
  51299. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51300. return this.position.y;
  51301. }
  51302. if (!this._heightQuads || this._heightQuads.length == 0) {
  51303. this._initHeightQuads();
  51304. this._computeHeightQuads();
  51305. }
  51306. var facet = this._getFacetAt(x, z);
  51307. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  51308. // return y in the World system
  51309. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  51310. return tmpVect.y;
  51311. };
  51312. /**
  51313. * Returns a normalized vector (Vector3) orthogonal to the ground
  51314. * at the ground coordinates (x, z) expressed in the World system.
  51315. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  51316. */
  51317. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  51318. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  51319. this.getNormalAtCoordinatesToRef(x, z, normal);
  51320. return normal;
  51321. };
  51322. /**
  51323. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  51324. * at the ground coordinates (x, z) expressed in the World system.
  51325. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  51326. * Returns the GroundMesh.
  51327. */
  51328. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  51329. var world = this.getWorldMatrix();
  51330. var tmpMat = BABYLON.Tmp.Matrix[5];
  51331. world.invertToRef(tmpMat);
  51332. var tmpVect = BABYLON.Tmp.Vector3[8];
  51333. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  51334. x = tmpVect.x;
  51335. z = tmpVect.z;
  51336. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  51337. return this;
  51338. }
  51339. if (!this._heightQuads || this._heightQuads.length == 0) {
  51340. this._initHeightQuads();
  51341. this._computeHeightQuads();
  51342. }
  51343. var facet = this._getFacetAt(x, z);
  51344. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  51345. return this;
  51346. };
  51347. /**
  51348. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  51349. * if the ground has been updated.
  51350. * This can be used in the render loop.
  51351. * Returns the GroundMesh.
  51352. */
  51353. GroundMesh.prototype.updateCoordinateHeights = function () {
  51354. if (!this._heightQuads || this._heightQuads.length == 0) {
  51355. this._initHeightQuads();
  51356. }
  51357. this._computeHeightQuads();
  51358. return this;
  51359. };
  51360. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  51361. GroundMesh.prototype._getFacetAt = function (x, z) {
  51362. // retrieve col and row from x, z coordinates in the ground local system
  51363. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  51364. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  51365. var quad = this._heightQuads[row * this._subdivisionsX + col];
  51366. var facet;
  51367. if (z < quad.slope.x * x + quad.slope.y) {
  51368. facet = quad.facet1;
  51369. }
  51370. else {
  51371. facet = quad.facet2;
  51372. }
  51373. return facet;
  51374. };
  51375. // Creates and populates the heightMap array with "facet" elements :
  51376. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  51377. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51378. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51379. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51380. // Returns the GroundMesh.
  51381. GroundMesh.prototype._initHeightQuads = function () {
  51382. var subdivisionsX = this._subdivisionsX;
  51383. var subdivisionsY = this._subdivisionsY;
  51384. this._heightQuads = new Array();
  51385. for (var row = 0; row < subdivisionsY; row++) {
  51386. for (var col = 0; col < subdivisionsX; col++) {
  51387. 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) };
  51388. this._heightQuads[row * subdivisionsX + col] = quad;
  51389. }
  51390. }
  51391. return this;
  51392. };
  51393. // Compute each quad element values and update the the heightMap array :
  51394. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51395. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51396. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51397. // Returns the GroundMesh.
  51398. GroundMesh.prototype._computeHeightQuads = function () {
  51399. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51400. if (!positions) {
  51401. return this;
  51402. }
  51403. var v1 = BABYLON.Tmp.Vector3[3];
  51404. var v2 = BABYLON.Tmp.Vector3[2];
  51405. var v3 = BABYLON.Tmp.Vector3[1];
  51406. var v4 = BABYLON.Tmp.Vector3[0];
  51407. var v1v2 = BABYLON.Tmp.Vector3[4];
  51408. var v1v3 = BABYLON.Tmp.Vector3[5];
  51409. var v1v4 = BABYLON.Tmp.Vector3[6];
  51410. var norm1 = BABYLON.Tmp.Vector3[7];
  51411. var norm2 = BABYLON.Tmp.Vector3[8];
  51412. var i = 0;
  51413. var j = 0;
  51414. var k = 0;
  51415. var cd = 0; // 2D slope coefficient : z = cd * x + h
  51416. var h = 0;
  51417. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  51418. var d2 = 0;
  51419. var subdivisionsX = this._subdivisionsX;
  51420. var subdivisionsY = this._subdivisionsY;
  51421. for (var row = 0; row < subdivisionsY; row++) {
  51422. for (var col = 0; col < subdivisionsX; col++) {
  51423. i = col * 3;
  51424. j = row * (subdivisionsX + 1) * 3;
  51425. k = (row + 1) * (subdivisionsX + 1) * 3;
  51426. v1.x = positions[j + i];
  51427. v1.y = positions[j + i + 1];
  51428. v1.z = positions[j + i + 2];
  51429. v2.x = positions[j + i + 3];
  51430. v2.y = positions[j + i + 4];
  51431. v2.z = positions[j + i + 5];
  51432. v3.x = positions[k + i];
  51433. v3.y = positions[k + i + 1];
  51434. v3.z = positions[k + i + 2];
  51435. v4.x = positions[k + i + 3];
  51436. v4.y = positions[k + i + 4];
  51437. v4.z = positions[k + i + 5];
  51438. // 2D slope V1V4
  51439. cd = (v4.z - v1.z) / (v4.x - v1.x);
  51440. h = v1.z - cd * v1.x; // v1 belongs to the slope
  51441. // facet equations :
  51442. // we compute each facet normal vector
  51443. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  51444. // we compute the value d by applying the equation to v1 which belongs to the plane
  51445. // then we store the facet equation in a Vector4
  51446. v2.subtractToRef(v1, v1v2);
  51447. v3.subtractToRef(v1, v1v3);
  51448. v4.subtractToRef(v1, v1v4);
  51449. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  51450. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  51451. norm1.normalize();
  51452. norm2.normalize();
  51453. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  51454. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  51455. var quad = this._heightQuads[row * subdivisionsX + col];
  51456. quad.slope.copyFromFloats(cd, h);
  51457. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  51458. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  51459. }
  51460. }
  51461. return this;
  51462. };
  51463. GroundMesh.prototype.serialize = function (serializationObject) {
  51464. _super.prototype.serialize.call(this, serializationObject);
  51465. serializationObject.subdivisionsX = this._subdivisionsX;
  51466. serializationObject.subdivisionsY = this._subdivisionsY;
  51467. serializationObject.minX = this._minX;
  51468. serializationObject.maxX = this._maxX;
  51469. serializationObject.minZ = this._minZ;
  51470. serializationObject.maxZ = this._maxZ;
  51471. serializationObject.width = this._width;
  51472. serializationObject.height = this._height;
  51473. };
  51474. GroundMesh.Parse = function (parsedMesh, scene) {
  51475. var result = new GroundMesh(parsedMesh.name, scene);
  51476. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  51477. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  51478. result._minX = parsedMesh.minX;
  51479. result._maxX = parsedMesh.maxX;
  51480. result._minZ = parsedMesh.minZ;
  51481. result._maxZ = parsedMesh.maxZ;
  51482. result._width = parsedMesh.width;
  51483. result._height = parsedMesh.height;
  51484. return result;
  51485. };
  51486. return GroundMesh;
  51487. }(BABYLON.Mesh));
  51488. BABYLON.GroundMesh = GroundMesh;
  51489. })(BABYLON || (BABYLON = {}));
  51490. //# sourceMappingURL=babylon.groundMesh.js.map
  51491. var BABYLON;
  51492. (function (BABYLON) {
  51493. /**
  51494. * Creates an instance based on a source mesh.
  51495. */
  51496. var InstancedMesh = /** @class */ (function (_super) {
  51497. __extends(InstancedMesh, _super);
  51498. function InstancedMesh(name, source) {
  51499. var _this = _super.call(this, name, source.getScene()) || this;
  51500. source.instances.push(_this);
  51501. _this._sourceMesh = source;
  51502. _this.position.copyFrom(source.position);
  51503. _this.rotation.copyFrom(source.rotation);
  51504. _this.scaling.copyFrom(source.scaling);
  51505. if (source.rotationQuaternion) {
  51506. _this.rotationQuaternion = source.rotationQuaternion.clone();
  51507. }
  51508. _this.infiniteDistance = source.infiniteDistance;
  51509. _this.setPivotMatrix(source.getPivotMatrix());
  51510. _this.refreshBoundingInfo();
  51511. _this._syncSubMeshes();
  51512. return _this;
  51513. }
  51514. /**
  51515. * Returns the string "InstancedMesh".
  51516. */
  51517. InstancedMesh.prototype.getClassName = function () {
  51518. return "InstancedMesh";
  51519. };
  51520. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  51521. // Methods
  51522. get: function () {
  51523. return this._sourceMesh.receiveShadows;
  51524. },
  51525. enumerable: true,
  51526. configurable: true
  51527. });
  51528. Object.defineProperty(InstancedMesh.prototype, "material", {
  51529. get: function () {
  51530. return this._sourceMesh.material;
  51531. },
  51532. enumerable: true,
  51533. configurable: true
  51534. });
  51535. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  51536. get: function () {
  51537. return this._sourceMesh.visibility;
  51538. },
  51539. enumerable: true,
  51540. configurable: true
  51541. });
  51542. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  51543. get: function () {
  51544. return this._sourceMesh.skeleton;
  51545. },
  51546. enumerable: true,
  51547. configurable: true
  51548. });
  51549. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  51550. get: function () {
  51551. return this._sourceMesh.renderingGroupId;
  51552. },
  51553. enumerable: true,
  51554. configurable: true
  51555. });
  51556. /**
  51557. * Returns the total number of vertices (integer).
  51558. */
  51559. InstancedMesh.prototype.getTotalVertices = function () {
  51560. return this._sourceMesh.getTotalVertices();
  51561. };
  51562. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  51563. get: function () {
  51564. return this._sourceMesh;
  51565. },
  51566. enumerable: true,
  51567. configurable: true
  51568. });
  51569. /**
  51570. * Is this node ready to be used/rendered
  51571. * @return {boolean} is it ready
  51572. */
  51573. InstancedMesh.prototype.isReady = function () {
  51574. return this._sourceMesh.isReady(true);
  51575. };
  51576. /**
  51577. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51578. */
  51579. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  51580. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  51581. };
  51582. /**
  51583. * Sets the vertex data of the mesh geometry for the requested `kind`.
  51584. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  51585. * The `data` are either a numeric array either a Float32Array.
  51586. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  51587. * 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).
  51588. * Note that a new underlying VertexBuffer object is created each call.
  51589. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  51590. *
  51591. * Possible `kind` values :
  51592. * - BABYLON.VertexBuffer.PositionKind
  51593. * - BABYLON.VertexBuffer.UVKind
  51594. * - BABYLON.VertexBuffer.UV2Kind
  51595. * - BABYLON.VertexBuffer.UV3Kind
  51596. * - BABYLON.VertexBuffer.UV4Kind
  51597. * - BABYLON.VertexBuffer.UV5Kind
  51598. * - BABYLON.VertexBuffer.UV6Kind
  51599. * - BABYLON.VertexBuffer.ColorKind
  51600. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51601. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51602. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51603. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51604. *
  51605. * Returns the Mesh.
  51606. */
  51607. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  51608. if (this.sourceMesh) {
  51609. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  51610. }
  51611. return this.sourceMesh;
  51612. };
  51613. /**
  51614. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  51615. * If the mesh has no geometry, it is simply returned as it is.
  51616. * The `data` are either a numeric array either a Float32Array.
  51617. * No new underlying VertexBuffer object is created.
  51618. * 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.
  51619. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  51620. *
  51621. * Possible `kind` values :
  51622. * - BABYLON.VertexBuffer.PositionKind
  51623. * - BABYLON.VertexBuffer.UVKind
  51624. * - BABYLON.VertexBuffer.UV2Kind
  51625. * - BABYLON.VertexBuffer.UV3Kind
  51626. * - BABYLON.VertexBuffer.UV4Kind
  51627. * - BABYLON.VertexBuffer.UV5Kind
  51628. * - BABYLON.VertexBuffer.UV6Kind
  51629. * - BABYLON.VertexBuffer.ColorKind
  51630. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51631. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51632. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51633. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51634. *
  51635. * Returns the Mesh.
  51636. */
  51637. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  51638. if (this.sourceMesh) {
  51639. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  51640. }
  51641. return this.sourceMesh;
  51642. };
  51643. /**
  51644. * Sets the mesh indices.
  51645. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  51646. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  51647. * This method creates a new index buffer each call.
  51648. * Returns the Mesh.
  51649. */
  51650. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  51651. if (totalVertices === void 0) { totalVertices = null; }
  51652. if (this.sourceMesh) {
  51653. this.sourceMesh.setIndices(indices, totalVertices);
  51654. }
  51655. return this.sourceMesh;
  51656. };
  51657. /**
  51658. * Boolean : True if the mesh owns the requested kind of data.
  51659. */
  51660. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  51661. return this._sourceMesh.isVerticesDataPresent(kind);
  51662. };
  51663. /**
  51664. * Returns an array of indices (IndicesArray).
  51665. */
  51666. InstancedMesh.prototype.getIndices = function () {
  51667. return this._sourceMesh.getIndices();
  51668. };
  51669. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  51670. get: function () {
  51671. return this._sourceMesh._positions;
  51672. },
  51673. enumerable: true,
  51674. configurable: true
  51675. });
  51676. /**
  51677. * Sets a new updated BoundingInfo to the mesh.
  51678. * Returns the mesh.
  51679. */
  51680. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51681. var meshBB = this._sourceMesh.getBoundingInfo();
  51682. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51683. this._updateBoundingInfo();
  51684. return this;
  51685. };
  51686. InstancedMesh.prototype._preActivate = function () {
  51687. if (this._currentLOD) {
  51688. this._currentLOD._preActivate();
  51689. }
  51690. return this;
  51691. };
  51692. InstancedMesh.prototype._activate = function (renderId) {
  51693. if (this._currentLOD) {
  51694. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51695. }
  51696. return this;
  51697. };
  51698. /**
  51699. * Returns the current associated LOD AbstractMesh.
  51700. */
  51701. InstancedMesh.prototype.getLOD = function (camera) {
  51702. if (!camera) {
  51703. return this;
  51704. }
  51705. var boundingInfo = this.getBoundingInfo();
  51706. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51707. if (this._currentLOD === this.sourceMesh) {
  51708. return this;
  51709. }
  51710. return this._currentLOD;
  51711. };
  51712. InstancedMesh.prototype._syncSubMeshes = function () {
  51713. this.releaseSubMeshes();
  51714. if (this._sourceMesh.subMeshes) {
  51715. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51716. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51717. }
  51718. }
  51719. return this;
  51720. };
  51721. InstancedMesh.prototype._generatePointsArray = function () {
  51722. return this._sourceMesh._generatePointsArray();
  51723. };
  51724. /**
  51725. * Creates a new InstancedMesh from the current mesh.
  51726. * - name (string) : the cloned mesh name
  51727. * - newParent (optional Node) : the optional Node to parent the clone to.
  51728. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51729. *
  51730. * Returns the clone.
  51731. */
  51732. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51733. var result = this._sourceMesh.createInstance(name);
  51734. // Deep copy
  51735. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51736. // Bounding info
  51737. this.refreshBoundingInfo();
  51738. // Parent
  51739. if (newParent) {
  51740. result.parent = newParent;
  51741. }
  51742. if (!doNotCloneChildren) {
  51743. // Children
  51744. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51745. var mesh = this.getScene().meshes[index];
  51746. if (mesh.parent === this) {
  51747. mesh.clone(mesh.name, result);
  51748. }
  51749. }
  51750. }
  51751. result.computeWorldMatrix(true);
  51752. return result;
  51753. };
  51754. /**
  51755. * Disposes the InstancedMesh.
  51756. * Returns nothing.
  51757. */
  51758. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51759. // Remove from mesh
  51760. var index = this._sourceMesh.instances.indexOf(this);
  51761. this._sourceMesh.instances.splice(index, 1);
  51762. _super.prototype.dispose.call(this, doNotRecurse);
  51763. };
  51764. return InstancedMesh;
  51765. }(BABYLON.AbstractMesh));
  51766. BABYLON.InstancedMesh = InstancedMesh;
  51767. })(BABYLON || (BABYLON = {}));
  51768. //# sourceMappingURL=babylon.instancedMesh.js.map
  51769. var BABYLON;
  51770. (function (BABYLON) {
  51771. var LinesMesh = /** @class */ (function (_super) {
  51772. __extends(LinesMesh, _super);
  51773. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  51774. if (scene === void 0) { scene = null; }
  51775. if (parent === void 0) { parent = null; }
  51776. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  51777. _this.useVertexColor = useVertexColor;
  51778. _this.useVertexAlpha = useVertexAlpha;
  51779. _this.color = new BABYLON.Color3(1, 1, 1);
  51780. _this.alpha = 1;
  51781. if (source) {
  51782. _this.color = source.color.clone();
  51783. _this.alpha = source.alpha;
  51784. _this.useVertexColor = source.useVertexColor;
  51785. _this.useVertexAlpha = source.useVertexAlpha;
  51786. }
  51787. _this._intersectionThreshold = 0.1;
  51788. var defines = [];
  51789. var options = {
  51790. attributes: [BABYLON.VertexBuffer.PositionKind],
  51791. uniforms: ["world", "viewProjection"],
  51792. needAlphaBlending: true,
  51793. defines: defines
  51794. };
  51795. if (useVertexAlpha === false) {
  51796. options.needAlphaBlending = false;
  51797. }
  51798. if (!useVertexColor) {
  51799. options.uniforms.push("color");
  51800. }
  51801. else {
  51802. options.defines.push("#define VERTEXCOLOR");
  51803. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  51804. }
  51805. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  51806. return _this;
  51807. }
  51808. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  51809. /**
  51810. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51811. * This margin is expressed in world space coordinates, so its value may vary.
  51812. * Default value is 0.1
  51813. * @returns the intersection Threshold value.
  51814. */
  51815. get: function () {
  51816. return this._intersectionThreshold;
  51817. },
  51818. /**
  51819. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51820. * This margin is expressed in world space coordinates, so its value may vary.
  51821. * @param value the new threshold to apply
  51822. */
  51823. set: function (value) {
  51824. if (this._intersectionThreshold === value) {
  51825. return;
  51826. }
  51827. this._intersectionThreshold = value;
  51828. if (this.geometry) {
  51829. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  51830. }
  51831. },
  51832. enumerable: true,
  51833. configurable: true
  51834. });
  51835. /**
  51836. * Returns the string "LineMesh"
  51837. */
  51838. LinesMesh.prototype.getClassName = function () {
  51839. return "LinesMesh";
  51840. };
  51841. Object.defineProperty(LinesMesh.prototype, "material", {
  51842. get: function () {
  51843. return this._colorShader;
  51844. },
  51845. set: function (value) {
  51846. // Do nothing
  51847. },
  51848. enumerable: true,
  51849. configurable: true
  51850. });
  51851. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  51852. get: function () {
  51853. return false;
  51854. },
  51855. enumerable: true,
  51856. configurable: true
  51857. });
  51858. LinesMesh.prototype.createInstance = function (name) {
  51859. throw new Error("LinesMeshes do not support createInstance.");
  51860. };
  51861. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  51862. if (!this._geometry) {
  51863. return this;
  51864. }
  51865. // VBOs
  51866. this._geometry._bind(this._colorShader.getEffect());
  51867. // Color
  51868. if (!this.useVertexColor) {
  51869. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  51870. }
  51871. return this;
  51872. };
  51873. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  51874. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  51875. return this;
  51876. }
  51877. var engine = this.getScene().getEngine();
  51878. // Draw order
  51879. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  51880. return this;
  51881. };
  51882. LinesMesh.prototype.dispose = function (doNotRecurse) {
  51883. this._colorShader.dispose();
  51884. _super.prototype.dispose.call(this, doNotRecurse);
  51885. };
  51886. /**
  51887. * Returns a new LineMesh object cloned from the current one.
  51888. */
  51889. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51890. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  51891. };
  51892. return LinesMesh;
  51893. }(BABYLON.Mesh));
  51894. BABYLON.LinesMesh = LinesMesh;
  51895. })(BABYLON || (BABYLON = {}));
  51896. //# sourceMappingURL=babylon.linesMesh.js.map
  51897. var BABYLON;
  51898. (function (BABYLON) {
  51899. var MeshBuilder = /** @class */ (function () {
  51900. function MeshBuilder() {
  51901. }
  51902. MeshBuilder.updateSideOrientation = function (orientation) {
  51903. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  51904. return BABYLON.Mesh.DOUBLESIDE;
  51905. }
  51906. if (orientation === undefined || orientation === null) {
  51907. return BABYLON.Mesh.FRONTSIDE;
  51908. }
  51909. return orientation;
  51910. };
  51911. /**
  51912. * Creates a box mesh.
  51913. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  51914. * The parameter `size` sets the size (float) of each box side (default 1).
  51915. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  51916. * 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).
  51917. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51918. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51919. * 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).
  51920. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51922. */
  51923. MeshBuilder.CreateBox = function (name, options, scene) {
  51924. if (scene === void 0) { scene = null; }
  51925. var box = new BABYLON.Mesh(name, scene);
  51926. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51927. box._originalBuilderSideOrientation = options.sideOrientation;
  51928. var vertexData = BABYLON.VertexData.CreateBox(options);
  51929. vertexData.applyToMesh(box, options.updatable);
  51930. return box;
  51931. };
  51932. /**
  51933. * Creates a sphere mesh.
  51934. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  51935. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  51936. * 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`).
  51937. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  51938. * 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
  51939. * 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).
  51940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51941. * 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).
  51942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51944. */
  51945. MeshBuilder.CreateSphere = function (name, options, scene) {
  51946. var sphere = new BABYLON.Mesh(name, scene);
  51947. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51948. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51949. var vertexData = BABYLON.VertexData.CreateSphere(options);
  51950. vertexData.applyToMesh(sphere, options.updatable);
  51951. return sphere;
  51952. };
  51953. /**
  51954. * Creates a plane polygonal mesh. By default, this is a disc.
  51955. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  51956. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  51957. * 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.
  51958. * 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
  51959. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51960. * 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).
  51961. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51963. */
  51964. MeshBuilder.CreateDisc = function (name, options, scene) {
  51965. if (scene === void 0) { scene = null; }
  51966. var disc = new BABYLON.Mesh(name, scene);
  51967. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51968. disc._originalBuilderSideOrientation = options.sideOrientation;
  51969. var vertexData = BABYLON.VertexData.CreateDisc(options);
  51970. vertexData.applyToMesh(disc, options.updatable);
  51971. return disc;
  51972. };
  51973. /**
  51974. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  51975. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  51976. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  51977. * 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`).
  51978. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  51979. * 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.
  51980. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51981. * 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).
  51982. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51984. */
  51985. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  51986. var sphere = new BABYLON.Mesh(name, scene);
  51987. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51988. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51989. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  51990. vertexData.applyToMesh(sphere, options.updatable);
  51991. return sphere;
  51992. };
  51993. ;
  51994. /**
  51995. * Creates a ribbon mesh.
  51996. * 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.
  51997. *
  51998. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  51999. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  52000. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  52001. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  52002. * 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.
  52003. * 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.
  52004. * 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
  52005. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52006. * 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).
  52007. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52008. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52009. * 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.
  52010. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  52011. * 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
  52012. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  52013. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  52014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52015. */
  52016. MeshBuilder.CreateRibbon = function (name, options, scene) {
  52017. if (scene === void 0) { scene = null; }
  52018. var pathArray = options.pathArray;
  52019. var closeArray = options.closeArray;
  52020. var closePath = options.closePath;
  52021. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52022. var instance = options.instance;
  52023. var updatable = options.updatable;
  52024. if (instance) {
  52025. // positionFunction : ribbon case
  52026. // only pathArray and sideOrientation parameters are taken into account for positions update
  52027. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  52028. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  52029. var positionFunction = function (positions) {
  52030. var minlg = pathArray[0].length;
  52031. var i = 0;
  52032. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  52033. for (var si = 1; si <= ns; si++) {
  52034. for (var p = 0; p < pathArray.length; p++) {
  52035. var path = pathArray[p];
  52036. var l = path.length;
  52037. minlg = (minlg < l) ? minlg : l;
  52038. var j = 0;
  52039. while (j < minlg) {
  52040. positions[i] = path[j].x;
  52041. positions[i + 1] = path[j].y;
  52042. positions[i + 2] = path[j].z;
  52043. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  52044. BABYLON.Tmp.Vector3[0].x = path[j].x;
  52045. }
  52046. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  52047. BABYLON.Tmp.Vector3[1].x = path[j].x;
  52048. }
  52049. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  52050. BABYLON.Tmp.Vector3[0].y = path[j].y;
  52051. }
  52052. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  52053. BABYLON.Tmp.Vector3[1].y = path[j].y;
  52054. }
  52055. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  52056. BABYLON.Tmp.Vector3[0].z = path[j].z;
  52057. }
  52058. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  52059. BABYLON.Tmp.Vector3[1].z = path[j].z;
  52060. }
  52061. j++;
  52062. i += 3;
  52063. }
  52064. if (instance._closePath) {
  52065. positions[i] = path[0].x;
  52066. positions[i + 1] = path[0].y;
  52067. positions[i + 2] = path[0].z;
  52068. i += 3;
  52069. }
  52070. }
  52071. }
  52072. };
  52073. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52074. positionFunction(positions);
  52075. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  52076. instance._boundingInfo.update(instance._worldMatrix);
  52077. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52078. if (options.colors) {
  52079. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52080. for (var c = 0; c < options.colors.length; c++) {
  52081. colors[c * 4] = options.colors[c].r;
  52082. colors[c * 4 + 1] = options.colors[c].g;
  52083. colors[c * 4 + 2] = options.colors[c].b;
  52084. colors[c * 4 + 3] = options.colors[c].a;
  52085. }
  52086. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  52087. }
  52088. if (options.uvs) {
  52089. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52090. for (var i = 0; i < options.uvs.length; i++) {
  52091. uvs[i * 2] = options.uvs[i].x;
  52092. uvs[i * 2 + 1] = options.uvs[i].y;
  52093. }
  52094. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  52095. }
  52096. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  52097. var indices = instance.getIndices();
  52098. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52099. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  52100. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  52101. if (instance._closePath) {
  52102. var indexFirst = 0;
  52103. var indexLast = 0;
  52104. for (var p = 0; p < pathArray.length; p++) {
  52105. indexFirst = instance._idx[p] * 3;
  52106. if (p + 1 < pathArray.length) {
  52107. indexLast = (instance._idx[p + 1] - 1) * 3;
  52108. }
  52109. else {
  52110. indexLast = normals.length - 3;
  52111. }
  52112. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  52113. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  52114. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  52115. normals[indexLast] = normals[indexFirst];
  52116. normals[indexLast + 1] = normals[indexFirst + 1];
  52117. normals[indexLast + 2] = normals[indexFirst + 2];
  52118. }
  52119. }
  52120. if (!(instance.areNormalsFrozen)) {
  52121. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  52122. }
  52123. }
  52124. return instance;
  52125. }
  52126. else {
  52127. var ribbon = new BABYLON.Mesh(name, scene);
  52128. ribbon._originalBuilderSideOrientation = sideOrientation;
  52129. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  52130. if (closePath) {
  52131. ribbon._idx = vertexData._idx;
  52132. }
  52133. ribbon._closePath = closePath;
  52134. ribbon._closeArray = closeArray;
  52135. vertexData.applyToMesh(ribbon, updatable);
  52136. return ribbon;
  52137. }
  52138. };
  52139. /**
  52140. * Creates a cylinder or a cone mesh.
  52141. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  52142. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  52143. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  52144. * 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.
  52145. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  52146. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  52147. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  52148. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  52149. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  52150. * 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).
  52151. * 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
  52152. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  52153. * 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
  52154. * 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.
  52155. * If `enclose` is false, a ring surface is one element.
  52156. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  52157. * 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
  52158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52159. * 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).
  52160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52162. */
  52163. MeshBuilder.CreateCylinder = function (name, options, scene) {
  52164. var cylinder = new BABYLON.Mesh(name, scene);
  52165. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52166. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  52167. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  52168. vertexData.applyToMesh(cylinder, options.updatable);
  52169. return cylinder;
  52170. };
  52171. /**
  52172. * Creates a torus mesh.
  52173. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  52174. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  52175. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  52176. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  52177. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52178. * 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).
  52179. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52181. */
  52182. MeshBuilder.CreateTorus = function (name, options, scene) {
  52183. var torus = new BABYLON.Mesh(name, scene);
  52184. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52185. torus._originalBuilderSideOrientation = options.sideOrientation;
  52186. var vertexData = BABYLON.VertexData.CreateTorus(options);
  52187. vertexData.applyToMesh(torus, options.updatable);
  52188. return torus;
  52189. };
  52190. /**
  52191. * Creates a torus knot mesh.
  52192. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  52193. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  52194. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  52195. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  52196. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  52197. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52198. * 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).
  52199. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52201. */
  52202. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  52203. var torusKnot = new BABYLON.Mesh(name, scene);
  52204. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52205. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  52206. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  52207. vertexData.applyToMesh(torusKnot, options.updatable);
  52208. return torusKnot;
  52209. };
  52210. /**
  52211. * Creates a line system mesh.
  52212. * A line system is a pool of many lines gathered in a single mesh.
  52213. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  52214. * 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.
  52215. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  52216. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  52217. * 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
  52218. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  52219. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  52220. * 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
  52221. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  52222. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52223. */
  52224. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  52225. var instance = options.instance;
  52226. var lines = options.lines;
  52227. var colors = options.colors;
  52228. if (instance) {
  52229. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52230. var vertexColor;
  52231. var lineColors;
  52232. if (colors) {
  52233. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52234. }
  52235. var i = 0;
  52236. var c = 0;
  52237. for (var l = 0; l < lines.length; l++) {
  52238. var points = lines[l];
  52239. for (var p = 0; p < points.length; p++) {
  52240. positions[i] = points[p].x;
  52241. positions[i + 1] = points[p].y;
  52242. positions[i + 2] = points[p].z;
  52243. if (colors && vertexColor) {
  52244. lineColors = colors[l];
  52245. vertexColor[c] = lineColors[p].r;
  52246. vertexColor[c + 1] = lineColors[p].g;
  52247. vertexColor[c + 2] = lineColors[p].b;
  52248. vertexColor[c + 3] = lineColors[p].a;
  52249. c += 4;
  52250. }
  52251. i += 3;
  52252. }
  52253. }
  52254. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  52255. if (colors && vertexColor) {
  52256. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  52257. }
  52258. return instance;
  52259. }
  52260. // line system creation
  52261. var useVertexColor = (colors) ? true : false;
  52262. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  52263. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  52264. vertexData.applyToMesh(lineSystem, options.updatable);
  52265. return lineSystem;
  52266. };
  52267. /**
  52268. * Creates a line mesh.
  52269. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  52270. * 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.
  52271. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52272. * The parameter `points` is an array successive Vector3.
  52273. * 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
  52274. * The optional parameter `colors` is an array of successive Color4, one per line point.
  52275. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  52276. * When updating an instance, remember that only point positions can change, not the number of points.
  52277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52278. */
  52279. MeshBuilder.CreateLines = function (name, options, scene) {
  52280. if (scene === void 0) { scene = null; }
  52281. var colors = (options.colors) ? [options.colors] : null;
  52282. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  52283. return lines;
  52284. };
  52285. /**
  52286. * Creates a dashed line mesh.
  52287. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  52288. * 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.
  52289. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  52290. * The parameter `points` is an array successive Vector3.
  52291. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  52292. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  52293. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  52294. * 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
  52295. * When updating an instance, remember that only point positions can change, not the number of points.
  52296. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52297. */
  52298. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  52299. if (scene === void 0) { scene = null; }
  52300. var points = options.points;
  52301. var instance = options.instance;
  52302. var gapSize = options.gapSize || 1;
  52303. var dashSize = options.dashSize || 3;
  52304. if (instance) {
  52305. var positionFunction = function (positions) {
  52306. var curvect = BABYLON.Vector3.Zero();
  52307. var nbSeg = positions.length / 6;
  52308. var lg = 0;
  52309. var nb = 0;
  52310. var shft = 0;
  52311. var dashshft = 0;
  52312. var curshft = 0;
  52313. var p = 0;
  52314. var i = 0;
  52315. var j = 0;
  52316. for (i = 0; i < points.length - 1; i++) {
  52317. points[i + 1].subtractToRef(points[i], curvect);
  52318. lg += curvect.length();
  52319. }
  52320. shft = lg / nbSeg;
  52321. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  52322. for (i = 0; i < points.length - 1; i++) {
  52323. points[i + 1].subtractToRef(points[i], curvect);
  52324. nb = Math.floor(curvect.length() / shft);
  52325. curvect.normalize();
  52326. j = 0;
  52327. while (j < nb && p < positions.length) {
  52328. curshft = shft * j;
  52329. positions[p] = points[i].x + curshft * curvect.x;
  52330. positions[p + 1] = points[i].y + curshft * curvect.y;
  52331. positions[p + 2] = points[i].z + curshft * curvect.z;
  52332. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  52333. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  52334. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  52335. p += 6;
  52336. j++;
  52337. }
  52338. }
  52339. while (p < positions.length) {
  52340. positions[p] = points[i].x;
  52341. positions[p + 1] = points[i].y;
  52342. positions[p + 2] = points[i].z;
  52343. p += 3;
  52344. }
  52345. };
  52346. instance.updateMeshPositions(positionFunction, false);
  52347. return instance;
  52348. }
  52349. // dashed lines creation
  52350. var dashedLines = new BABYLON.LinesMesh(name, scene);
  52351. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  52352. vertexData.applyToMesh(dashedLines, options.updatable);
  52353. dashedLines.dashSize = dashSize;
  52354. dashedLines.gapSize = gapSize;
  52355. return dashedLines;
  52356. };
  52357. /**
  52358. * Creates an extruded shape mesh.
  52359. * 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.
  52360. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  52361. *
  52362. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52363. * 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
  52364. * extruded along the Z axis.
  52365. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52366. * 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.
  52367. * The parameter `scale` (float, default 1) is the value to scale the shape.
  52368. * 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
  52369. * 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
  52370. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52372. * 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).
  52373. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52374. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52376. */
  52377. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  52378. if (scene === void 0) { scene = null; }
  52379. var path = options.path;
  52380. var shape = options.shape;
  52381. var scale = options.scale || 1;
  52382. var rotation = options.rotation || 0;
  52383. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52384. var updatable = options.updatable;
  52385. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52386. var instance = options.instance || null;
  52387. var invertUV = options.invertUV || false;
  52388. 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);
  52389. };
  52390. /**
  52391. * Creates an custom extruded shape mesh.
  52392. * 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.
  52393. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  52394. *
  52395. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52396. * 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
  52397. * extruded along the Z axis.
  52398. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52399. * 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
  52400. * and the distance of this point from the begining of the path :
  52401. * ```javascript
  52402. * var rotationFunction = function(i, distance) {
  52403. * // do things
  52404. * return rotationValue; }
  52405. * ```
  52406. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  52407. * 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
  52408. * and the distance of this point from the begining of the path :
  52409. * ```javascript
  52410. * var scaleFunction = function(i, distance) {
  52411. * // do things
  52412. * return scaleValue;}
  52413. * ```
  52414. * It must returns a float value that will be the scale value applied to the shape on each path point.
  52415. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  52416. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  52417. * 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
  52418. * 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
  52419. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52421. * 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).
  52422. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52423. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52425. */
  52426. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  52427. var path = options.path;
  52428. var shape = options.shape;
  52429. var scaleFunction = options.scaleFunction || (function () { return 1; });
  52430. var rotationFunction = options.rotationFunction || (function () { return 0; });
  52431. var ribbonCloseArray = options.ribbonCloseArray || false;
  52432. var ribbonClosePath = options.ribbonClosePath || false;
  52433. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52434. var updatable = options.updatable;
  52435. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52436. var instance = options.instance;
  52437. var invertUV = options.invertUV || false;
  52438. 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);
  52439. };
  52440. /**
  52441. * Creates lathe mesh.
  52442. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  52443. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  52444. *
  52445. * 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
  52446. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  52447. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  52448. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  52449. * 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.
  52450. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  52451. * 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
  52452. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52453. * 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).
  52454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52455. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52457. */
  52458. MeshBuilder.CreateLathe = function (name, options, scene) {
  52459. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  52460. var closed = (options.closed === undefined) ? true : options.closed;
  52461. var shape = options.shape;
  52462. var radius = options.radius || 1;
  52463. var tessellation = options.tessellation || 64;
  52464. var updatable = options.updatable;
  52465. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52466. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52467. var pi2 = Math.PI * 2;
  52468. var paths = new Array();
  52469. var invertUV = options.invertUV || false;
  52470. var i = 0;
  52471. var p = 0;
  52472. var step = pi2 / tessellation * arc;
  52473. var rotated;
  52474. var path = new Array();
  52475. ;
  52476. for (i = 0; i <= tessellation; i++) {
  52477. var path = [];
  52478. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  52479. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  52480. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  52481. }
  52482. for (p = 0; p < shape.length; p++) {
  52483. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  52484. path.push(rotated);
  52485. }
  52486. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  52487. 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));
  52488. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  52489. }
  52490. paths.push(path);
  52491. }
  52492. // lathe ribbon
  52493. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52494. return lathe;
  52495. };
  52496. /**
  52497. * Creates a plane mesh.
  52498. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52499. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  52500. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  52501. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  52502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52503. * 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).
  52504. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52506. */
  52507. MeshBuilder.CreatePlane = function (name, options, scene) {
  52508. var plane = new BABYLON.Mesh(name, scene);
  52509. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52510. plane._originalBuilderSideOrientation = options.sideOrientation;
  52511. var vertexData = BABYLON.VertexData.CreatePlane(options);
  52512. vertexData.applyToMesh(plane, options.updatable);
  52513. if (options.sourcePlane) {
  52514. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  52515. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  52516. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  52517. plane.rotate(vectorProduct, product);
  52518. }
  52519. return plane;
  52520. };
  52521. /**
  52522. * Creates a ground mesh.
  52523. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52524. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  52525. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  52526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52527. */
  52528. MeshBuilder.CreateGround = function (name, options, scene) {
  52529. var ground = new BABYLON.GroundMesh(name, scene);
  52530. ground._setReady(false);
  52531. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  52532. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  52533. ground._width = options.width || 1;
  52534. ground._height = options.height || 1;
  52535. ground._maxX = ground._width / 2;
  52536. ground._maxZ = ground._height / 2;
  52537. ground._minX = -ground._maxX;
  52538. ground._minZ = -ground._maxZ;
  52539. var vertexData = BABYLON.VertexData.CreateGround(options);
  52540. vertexData.applyToMesh(ground, options.updatable);
  52541. ground._setReady(true);
  52542. return ground;
  52543. };
  52544. /**
  52545. * Creates a tiled ground mesh.
  52546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  52547. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  52548. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  52549. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  52550. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  52551. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  52552. * numbers of subdivisions on the ground width and height of each tile.
  52553. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52554. */
  52555. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  52556. var tiledGround = new BABYLON.Mesh(name, scene);
  52557. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  52558. vertexData.applyToMesh(tiledGround, options.updatable);
  52559. return tiledGround;
  52560. };
  52561. /**
  52562. * Creates a ground mesh from a height map.
  52563. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  52564. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  52565. * The parameter `url` sets the URL of the height map image resource.
  52566. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  52567. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  52568. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  52569. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  52570. * 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.
  52571. * 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).
  52572. * This function is passed the newly built mesh :
  52573. * ```javascript
  52574. * function(mesh) { // do things
  52575. * return; }
  52576. * ```
  52577. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52578. */
  52579. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  52580. var width = options.width || 10.0;
  52581. var height = options.height || 10.0;
  52582. var subdivisions = options.subdivisions || 1 | 0;
  52583. var minHeight = options.minHeight || 0.0;
  52584. var maxHeight = options.maxHeight || 1.0;
  52585. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  52586. var updatable = options.updatable;
  52587. var onReady = options.onReady;
  52588. var ground = new BABYLON.GroundMesh(name, scene);
  52589. ground._subdivisionsX = subdivisions;
  52590. ground._subdivisionsY = subdivisions;
  52591. ground._width = width;
  52592. ground._height = height;
  52593. ground._maxX = ground._width / 2.0;
  52594. ground._maxZ = ground._height / 2.0;
  52595. ground._minX = -ground._maxX;
  52596. ground._minZ = -ground._maxZ;
  52597. ground._setReady(false);
  52598. var onload = function (img) {
  52599. // Getting height map data
  52600. var canvas = document.createElement("canvas");
  52601. var context = canvas.getContext("2d");
  52602. if (!context) {
  52603. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  52604. }
  52605. if (scene.isDisposed) {
  52606. return;
  52607. }
  52608. var bufferWidth = img.width;
  52609. var bufferHeight = img.height;
  52610. canvas.width = bufferWidth;
  52611. canvas.height = bufferHeight;
  52612. context.drawImage(img, 0, 0);
  52613. // Create VertexData from map data
  52614. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  52615. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  52616. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  52617. width: width, height: height,
  52618. subdivisions: subdivisions,
  52619. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  52620. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  52621. });
  52622. vertexData.applyToMesh(ground, updatable);
  52623. ground._setReady(true);
  52624. //execute ready callback, if set
  52625. if (onReady) {
  52626. onReady(ground);
  52627. }
  52628. };
  52629. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  52630. return ground;
  52631. };
  52632. /**
  52633. * Creates a polygon mesh.
  52634. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  52635. * 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.
  52636. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52638. * 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).
  52639. * Remember you can only change the shape positions, not their number when updating a polygon.
  52640. */
  52641. MeshBuilder.CreatePolygon = function (name, options, scene) {
  52642. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52643. var shape = options.shape;
  52644. var holes = options.holes || [];
  52645. var depth = options.depth || 0;
  52646. var contours = [];
  52647. var hole = [];
  52648. for (var i = 0; i < shape.length; i++) {
  52649. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  52650. }
  52651. var epsilon = 0.00000001;
  52652. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  52653. contours.pop();
  52654. }
  52655. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  52656. for (var hNb = 0; hNb < holes.length; hNb++) {
  52657. hole = [];
  52658. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  52659. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  52660. }
  52661. polygonTriangulation.addHole(hole);
  52662. }
  52663. var polygon = polygonTriangulation.build(options.updatable, depth);
  52664. polygon._originalBuilderSideOrientation = options.sideOrientation;
  52665. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  52666. vertexData.applyToMesh(polygon, options.updatable);
  52667. return polygon;
  52668. };
  52669. ;
  52670. /**
  52671. * Creates an extruded polygon mesh, with depth in the Y direction.
  52672. * 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).
  52673. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52674. */
  52675. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52676. return MeshBuilder.CreatePolygon(name, options, scene);
  52677. };
  52678. ;
  52679. /**
  52680. * Creates a tube mesh.
  52681. * 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.
  52682. *
  52683. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52684. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52685. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52686. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52687. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52688. * 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.
  52689. * It must return a radius value (positive float) :
  52690. * ```javascript
  52691. * var radiusFunction = function(i, distance) {
  52692. * // do things
  52693. * return radius; }
  52694. * ```
  52695. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52696. * 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
  52697. * 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
  52698. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52699. * 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).
  52700. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52701. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52703. */
  52704. MeshBuilder.CreateTube = function (name, options, scene) {
  52705. var path = options.path;
  52706. var instance = options.instance;
  52707. var radius = 1.0;
  52708. if (instance) {
  52709. radius = instance.radius;
  52710. }
  52711. if (options.radius !== undefined) {
  52712. radius = options.radius;
  52713. }
  52714. ;
  52715. var tessellation = options.tessellation || 64 | 0;
  52716. var radiusFunction = options.radiusFunction || null;
  52717. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52718. var invertUV = options.invertUV || false;
  52719. var updatable = options.updatable;
  52720. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52721. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52722. // tube geometry
  52723. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52724. var tangents = path3D.getTangents();
  52725. var normals = path3D.getNormals();
  52726. var distances = path3D.getDistances();
  52727. var pi2 = Math.PI * 2;
  52728. var step = pi2 / tessellation * arc;
  52729. var returnRadius = function () { return radius; };
  52730. var radiusFunctionFinal = radiusFunction || returnRadius;
  52731. var circlePath;
  52732. var rad;
  52733. var normal;
  52734. var rotated;
  52735. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52736. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52737. for (var i = 0; i < path.length; i++) {
  52738. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52739. circlePath = Array(); // current circle array
  52740. normal = normals[i]; // current normal
  52741. for (var t = 0; t < tessellation; t++) {
  52742. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52743. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52744. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52745. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52746. circlePath[t] = rotated;
  52747. }
  52748. circlePaths[index] = circlePath;
  52749. index++;
  52750. }
  52751. // cap
  52752. var capPath = function (nbPoints, pathIndex) {
  52753. var pointCap = Array();
  52754. for (var i = 0; i < nbPoints; i++) {
  52755. pointCap.push(path[pathIndex]);
  52756. }
  52757. return pointCap;
  52758. };
  52759. switch (cap) {
  52760. case BABYLON.Mesh.NO_CAP:
  52761. break;
  52762. case BABYLON.Mesh.CAP_START:
  52763. circlePaths[0] = capPath(tessellation, 0);
  52764. circlePaths[1] = circlePaths[2].slice(0);
  52765. break;
  52766. case BABYLON.Mesh.CAP_END:
  52767. circlePaths[index] = circlePaths[index - 1].slice(0);
  52768. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52769. break;
  52770. case BABYLON.Mesh.CAP_ALL:
  52771. circlePaths[0] = capPath(tessellation, 0);
  52772. circlePaths[1] = circlePaths[2].slice(0);
  52773. circlePaths[index] = circlePaths[index - 1].slice(0);
  52774. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52775. break;
  52776. default:
  52777. break;
  52778. }
  52779. return circlePaths;
  52780. };
  52781. var path3D;
  52782. var pathArray;
  52783. if (instance) {
  52784. var arc = options.arc || instance.arc;
  52785. path3D = (instance.path3D).update(path);
  52786. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  52787. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  52788. instance.path3D = path3D;
  52789. instance.pathArray = pathArray;
  52790. instance.arc = arc;
  52791. instance.radius = radius;
  52792. return instance;
  52793. }
  52794. // tube creation
  52795. path3D = new BABYLON.Path3D(path);
  52796. var newPathArray = new Array();
  52797. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52798. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  52799. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52800. tube.pathArray = pathArray;
  52801. tube.path3D = path3D;
  52802. tube.tessellation = tessellation;
  52803. tube.cap = cap;
  52804. tube.arc = options.arc;
  52805. tube.radius = radius;
  52806. return tube;
  52807. };
  52808. /**
  52809. * Creates a polyhedron mesh.
  52810. *
  52811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  52812. * 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
  52813. * to choose the wanted type.
  52814. * The parameter `size` (positive float, default 1) sets the polygon size.
  52815. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  52816. * 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`.
  52817. * 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
  52818. * 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)`).
  52819. * 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
  52820. * 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.
  52821. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52822. * 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).
  52823. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52824. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52825. */
  52826. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  52827. var polyhedron = new BABYLON.Mesh(name, scene);
  52828. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52829. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  52830. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  52831. vertexData.applyToMesh(polyhedron, options.updatable);
  52832. return polyhedron;
  52833. };
  52834. /**
  52835. * Creates a decal mesh.
  52836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  52837. * 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.
  52838. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  52839. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  52840. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  52841. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  52842. */
  52843. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  52844. var indices = sourceMesh.getIndices();
  52845. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52846. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52847. var position = options.position || BABYLON.Vector3.Zero();
  52848. var normal = options.normal || BABYLON.Vector3.Up();
  52849. var size = options.size || BABYLON.Vector3.One();
  52850. var angle = options.angle || 0;
  52851. // Getting correct rotation
  52852. if (!normal) {
  52853. var target = new BABYLON.Vector3(0, 0, 1);
  52854. var camera = sourceMesh.getScene().activeCamera;
  52855. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  52856. normal = camera.globalPosition.subtract(cameraWorldTarget);
  52857. }
  52858. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  52859. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  52860. var pitch = Math.atan2(normal.y, len);
  52861. // Matrix
  52862. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  52863. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  52864. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  52865. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  52866. var vertexData = new BABYLON.VertexData();
  52867. vertexData.indices = [];
  52868. vertexData.positions = [];
  52869. vertexData.normals = [];
  52870. vertexData.uvs = [];
  52871. var currentVertexDataIndex = 0;
  52872. var extractDecalVector3 = function (indexId) {
  52873. var result = new BABYLON.PositionNormalVertex();
  52874. if (!indices || !positions || !normals) {
  52875. return result;
  52876. }
  52877. var vertexId = indices[indexId];
  52878. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  52879. // Send vector to decal local world
  52880. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  52881. // Get normal
  52882. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  52883. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  52884. return result;
  52885. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  52886. var clip = function (vertices, axis) {
  52887. if (vertices.length === 0) {
  52888. return vertices;
  52889. }
  52890. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  52891. var clipVertices = function (v0, v1) {
  52892. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  52893. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  52894. };
  52895. var result = new Array();
  52896. for (var index = 0; index < vertices.length; index += 3) {
  52897. var v1Out;
  52898. var v2Out;
  52899. var v3Out;
  52900. var total = 0;
  52901. var nV1 = null;
  52902. var nV2 = null;
  52903. var nV3 = null;
  52904. var nV4 = null;
  52905. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  52906. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  52907. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  52908. v1Out = d1 > 0;
  52909. v2Out = d2 > 0;
  52910. v3Out = d3 > 0;
  52911. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  52912. switch (total) {
  52913. case 0:
  52914. result.push(vertices[index]);
  52915. result.push(vertices[index + 1]);
  52916. result.push(vertices[index + 2]);
  52917. break;
  52918. case 1:
  52919. if (v1Out) {
  52920. nV1 = vertices[index + 1];
  52921. nV2 = vertices[index + 2];
  52922. nV3 = clipVertices(vertices[index], nV1);
  52923. nV4 = clipVertices(vertices[index], nV2);
  52924. }
  52925. if (v2Out) {
  52926. nV1 = vertices[index];
  52927. nV2 = vertices[index + 2];
  52928. nV3 = clipVertices(vertices[index + 1], nV1);
  52929. nV4 = clipVertices(vertices[index + 1], nV2);
  52930. result.push(nV3);
  52931. result.push(nV2.clone());
  52932. result.push(nV1.clone());
  52933. result.push(nV2.clone());
  52934. result.push(nV3.clone());
  52935. result.push(nV4);
  52936. break;
  52937. }
  52938. if (v3Out) {
  52939. nV1 = vertices[index];
  52940. nV2 = vertices[index + 1];
  52941. nV3 = clipVertices(vertices[index + 2], nV1);
  52942. nV4 = clipVertices(vertices[index + 2], nV2);
  52943. }
  52944. if (nV1 && nV2 && nV3 && nV4) {
  52945. result.push(nV1.clone());
  52946. result.push(nV2.clone());
  52947. result.push(nV3);
  52948. result.push(nV4);
  52949. result.push(nV3.clone());
  52950. result.push(nV2.clone());
  52951. }
  52952. break;
  52953. case 2:
  52954. if (!v1Out) {
  52955. nV1 = vertices[index].clone();
  52956. nV2 = clipVertices(nV1, vertices[index + 1]);
  52957. nV3 = clipVertices(nV1, vertices[index + 2]);
  52958. result.push(nV1);
  52959. result.push(nV2);
  52960. result.push(nV3);
  52961. }
  52962. if (!v2Out) {
  52963. nV1 = vertices[index + 1].clone();
  52964. nV2 = clipVertices(nV1, vertices[index + 2]);
  52965. nV3 = clipVertices(nV1, vertices[index]);
  52966. result.push(nV1);
  52967. result.push(nV2);
  52968. result.push(nV3);
  52969. }
  52970. if (!v3Out) {
  52971. nV1 = vertices[index + 2].clone();
  52972. nV2 = clipVertices(nV1, vertices[index]);
  52973. nV3 = clipVertices(nV1, vertices[index + 1]);
  52974. result.push(nV1);
  52975. result.push(nV2);
  52976. result.push(nV3);
  52977. }
  52978. break;
  52979. case 3:
  52980. break;
  52981. }
  52982. }
  52983. return result;
  52984. };
  52985. for (var index = 0; index < indices.length; index += 3) {
  52986. var faceVertices = new Array();
  52987. faceVertices.push(extractDecalVector3(index));
  52988. faceVertices.push(extractDecalVector3(index + 1));
  52989. faceVertices.push(extractDecalVector3(index + 2));
  52990. // Clip
  52991. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  52992. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  52993. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  52994. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  52995. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  52996. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  52997. if (faceVertices.length === 0) {
  52998. continue;
  52999. }
  53000. // Add UVs and get back to world
  53001. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  53002. var vertex = faceVertices[vIndex];
  53003. //TODO check for Int32Array | Uint32Array | Uint16Array
  53004. vertexData.indices.push(currentVertexDataIndex);
  53005. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  53006. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  53007. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  53008. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  53009. currentVertexDataIndex++;
  53010. }
  53011. }
  53012. // Return mesh
  53013. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  53014. vertexData.applyToMesh(decal);
  53015. decal.position = position.clone();
  53016. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  53017. return decal;
  53018. };
  53019. // Privates
  53020. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  53021. // extrusion geometry
  53022. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  53023. var tangents = path3D.getTangents();
  53024. var normals = path3D.getNormals();
  53025. var binormals = path3D.getBinormals();
  53026. var distances = path3D.getDistances();
  53027. var angle = 0;
  53028. var returnScale = function () { return scale !== null ? scale : 1; };
  53029. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  53030. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  53031. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  53032. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  53033. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  53034. for (var i = 0; i < curve.length; i++) {
  53035. var shapePath = new Array();
  53036. var angleStep = rotate(i, distances[i]);
  53037. var scaleRatio = scl(i, distances[i]);
  53038. for (var p = 0; p < shape.length; p++) {
  53039. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  53040. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  53041. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  53042. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  53043. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  53044. shapePath[p] = rotated;
  53045. }
  53046. shapePaths[index] = shapePath;
  53047. angle += angleStep;
  53048. index++;
  53049. }
  53050. // cap
  53051. var capPath = function (shapePath) {
  53052. var pointCap = Array();
  53053. var barycenter = BABYLON.Vector3.Zero();
  53054. var i;
  53055. for (i = 0; i < shapePath.length; i++) {
  53056. barycenter.addInPlace(shapePath[i]);
  53057. }
  53058. barycenter.scaleInPlace(1.0 / shapePath.length);
  53059. for (i = 0; i < shapePath.length; i++) {
  53060. pointCap.push(barycenter);
  53061. }
  53062. return pointCap;
  53063. };
  53064. switch (cap) {
  53065. case BABYLON.Mesh.NO_CAP:
  53066. break;
  53067. case BABYLON.Mesh.CAP_START:
  53068. shapePaths[0] = capPath(shapePaths[2]);
  53069. shapePaths[1] = shapePaths[2];
  53070. break;
  53071. case BABYLON.Mesh.CAP_END:
  53072. shapePaths[index] = shapePaths[index - 1];
  53073. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53074. break;
  53075. case BABYLON.Mesh.CAP_ALL:
  53076. shapePaths[0] = capPath(shapePaths[2]);
  53077. shapePaths[1] = shapePaths[2];
  53078. shapePaths[index] = shapePaths[index - 1];
  53079. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  53080. break;
  53081. default:
  53082. break;
  53083. }
  53084. return shapePaths;
  53085. };
  53086. var path3D;
  53087. var pathArray;
  53088. if (instance) {
  53089. path3D = (instance.path3D).update(curve);
  53090. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  53091. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  53092. return instance;
  53093. }
  53094. // extruded shape creation
  53095. path3D = new BABYLON.Path3D(curve);
  53096. var newShapePaths = new Array();
  53097. cap = (cap < 0 || cap > 3) ? 0 : cap;
  53098. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  53099. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  53100. extrudedGeneric.pathArray = pathArray;
  53101. extrudedGeneric.path3D = path3D;
  53102. extrudedGeneric.cap = cap;
  53103. return extrudedGeneric;
  53104. };
  53105. return MeshBuilder;
  53106. }());
  53107. BABYLON.MeshBuilder = MeshBuilder;
  53108. })(BABYLON || (BABYLON = {}));
  53109. //# sourceMappingURL=babylon.meshBuilder.js.map
  53110. var BABYLON;
  53111. (function (BABYLON) {
  53112. var AudioEngine = /** @class */ (function () {
  53113. function AudioEngine() {
  53114. this._audioContext = null;
  53115. this._audioContextInitialized = false;
  53116. this.canUseWebAudio = false;
  53117. this.WarnedWebAudioUnsupported = false;
  53118. this.unlocked = false;
  53119. this.isMP3supported = false;
  53120. this.isOGGsupported = false;
  53121. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  53122. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  53123. this.canUseWebAudio = true;
  53124. }
  53125. var audioElem = document.createElement('audio');
  53126. try {
  53127. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  53128. this.isMP3supported = true;
  53129. }
  53130. }
  53131. catch (e) {
  53132. // protect error during capability check.
  53133. }
  53134. try {
  53135. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  53136. this.isOGGsupported = true;
  53137. }
  53138. }
  53139. catch (e) {
  53140. // protect error during capability check.
  53141. }
  53142. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  53143. this._unlockiOSaudio();
  53144. }
  53145. else {
  53146. this.unlocked = true;
  53147. }
  53148. }
  53149. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  53150. get: function () {
  53151. if (!this._audioContextInitialized) {
  53152. this._initializeAudioContext();
  53153. }
  53154. return this._audioContext;
  53155. },
  53156. enumerable: true,
  53157. configurable: true
  53158. });
  53159. AudioEngine.prototype._unlockiOSaudio = function () {
  53160. var _this = this;
  53161. var unlockaudio = function () {
  53162. if (!_this.audioContext) {
  53163. return;
  53164. }
  53165. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  53166. var source = _this.audioContext.createBufferSource();
  53167. source.buffer = buffer;
  53168. source.connect(_this.audioContext.destination);
  53169. source.start(0);
  53170. setTimeout(function () {
  53171. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  53172. _this.unlocked = true;
  53173. window.removeEventListener('touchend', unlockaudio, false);
  53174. if (_this.onAudioUnlocked) {
  53175. _this.onAudioUnlocked();
  53176. }
  53177. }
  53178. }, 0);
  53179. };
  53180. window.addEventListener('touchend', unlockaudio, false);
  53181. };
  53182. AudioEngine.prototype._initializeAudioContext = function () {
  53183. try {
  53184. if (this.canUseWebAudio) {
  53185. this._audioContext = new AudioContext();
  53186. // create a global volume gain node
  53187. this.masterGain = this._audioContext.createGain();
  53188. this.masterGain.gain.value = 1;
  53189. this.masterGain.connect(this._audioContext.destination);
  53190. this._audioContextInitialized = true;
  53191. }
  53192. }
  53193. catch (e) {
  53194. this.canUseWebAudio = false;
  53195. BABYLON.Tools.Error("Web Audio: " + e.message);
  53196. }
  53197. };
  53198. AudioEngine.prototype.dispose = function () {
  53199. if (this.canUseWebAudio && this._audioContextInitialized) {
  53200. if (this._connectedAnalyser && this._audioContext) {
  53201. this._connectedAnalyser.stopDebugCanvas();
  53202. this._connectedAnalyser.dispose();
  53203. this.masterGain.disconnect();
  53204. this.masterGain.connect(this._audioContext.destination);
  53205. this._connectedAnalyser = null;
  53206. }
  53207. this.masterGain.gain.value = 1;
  53208. }
  53209. this.WarnedWebAudioUnsupported = false;
  53210. };
  53211. AudioEngine.prototype.getGlobalVolume = function () {
  53212. if (this.canUseWebAudio && this._audioContextInitialized) {
  53213. return this.masterGain.gain.value;
  53214. }
  53215. else {
  53216. return -1;
  53217. }
  53218. };
  53219. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  53220. if (this.canUseWebAudio && this._audioContextInitialized) {
  53221. this.masterGain.gain.value = newVolume;
  53222. }
  53223. };
  53224. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  53225. if (this._connectedAnalyser) {
  53226. this._connectedAnalyser.stopDebugCanvas();
  53227. }
  53228. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  53229. this._connectedAnalyser = analyser;
  53230. this.masterGain.disconnect();
  53231. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  53232. }
  53233. };
  53234. return AudioEngine;
  53235. }());
  53236. BABYLON.AudioEngine = AudioEngine;
  53237. })(BABYLON || (BABYLON = {}));
  53238. //# sourceMappingURL=babylon.audioEngine.js.map
  53239. var BABYLON;
  53240. (function (BABYLON) {
  53241. var Sound = /** @class */ (function () {
  53242. /**
  53243. * Create a sound and attach it to a scene
  53244. * @param name Name of your sound
  53245. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  53246. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  53247. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  53248. */
  53249. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  53250. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  53251. var _this = this;
  53252. this.autoplay = false;
  53253. this.loop = false;
  53254. this.useCustomAttenuation = false;
  53255. this.spatialSound = false;
  53256. this.refDistance = 1;
  53257. this.rolloffFactor = 1;
  53258. this.maxDistance = 100;
  53259. this.distanceModel = "linear";
  53260. this._panningModel = "equalpower";
  53261. this._playbackRate = 1;
  53262. this._streaming = false;
  53263. this._startTime = 0;
  53264. this._startOffset = 0;
  53265. this._position = BABYLON.Vector3.Zero();
  53266. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  53267. this._volume = 1;
  53268. this._isReadyToPlay = false;
  53269. this.isPlaying = false;
  53270. this.isPaused = false;
  53271. this._isDirectional = false;
  53272. // Used if you'd like to create a directional sound.
  53273. // If not set, the sound will be omnidirectional
  53274. this._coneInnerAngle = 360;
  53275. this._coneOuterAngle = 360;
  53276. this._coneOuterGain = 0;
  53277. this._isOutputConnected = false;
  53278. this._urlType = "Unknown";
  53279. this.name = name;
  53280. this._scene = scene;
  53281. this._readyToPlayCallback = readyToPlayCallback;
  53282. // Default custom attenuation function is a linear attenuation
  53283. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  53284. if (currentDistance < maxDistance) {
  53285. return currentVolume * (1 - currentDistance / maxDistance);
  53286. }
  53287. else {
  53288. return 0;
  53289. }
  53290. };
  53291. if (options) {
  53292. this.autoplay = options.autoplay || false;
  53293. this.loop = options.loop || false;
  53294. // if volume === 0, we need another way to check this option
  53295. if (options.volume !== undefined) {
  53296. this._volume = options.volume;
  53297. }
  53298. this.spatialSound = options.spatialSound || false;
  53299. this.maxDistance = options.maxDistance || 100;
  53300. this.useCustomAttenuation = options.useCustomAttenuation || false;
  53301. this.rolloffFactor = options.rolloffFactor || 1;
  53302. this.refDistance = options.refDistance || 1;
  53303. this.distanceModel = options.distanceModel || "linear";
  53304. this._playbackRate = options.playbackRate || 1;
  53305. this._streaming = options.streaming || false;
  53306. }
  53307. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53308. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  53309. this._soundGain.gain.value = this._volume;
  53310. this._inputAudioNode = this._soundGain;
  53311. this._ouputAudioNode = this._soundGain;
  53312. if (this.spatialSound) {
  53313. this._createSpatialParameters();
  53314. }
  53315. this._scene.mainSoundTrack.AddSound(this);
  53316. var validParameter = true;
  53317. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  53318. if (urlOrArrayBuffer) {
  53319. if (typeof (urlOrArrayBuffer) === "string")
  53320. this._urlType = "String";
  53321. if (Array.isArray(urlOrArrayBuffer))
  53322. this._urlType = "Array";
  53323. if (urlOrArrayBuffer instanceof ArrayBuffer)
  53324. this._urlType = "ArrayBuffer";
  53325. var urls = [];
  53326. var codecSupportedFound = false;
  53327. switch (this._urlType) {
  53328. case "ArrayBuffer":
  53329. if (urlOrArrayBuffer.byteLength > 0) {
  53330. codecSupportedFound = true;
  53331. this._soundLoaded(urlOrArrayBuffer);
  53332. }
  53333. break;
  53334. case "String":
  53335. urls.push(urlOrArrayBuffer);
  53336. case "Array":
  53337. if (urls.length === 0)
  53338. urls = urlOrArrayBuffer;
  53339. // If we found a supported format, we load it immediately and stop the loop
  53340. for (var i = 0; i < urls.length; i++) {
  53341. var url = urls[i];
  53342. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  53343. codecSupportedFound = true;
  53344. }
  53345. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  53346. codecSupportedFound = true;
  53347. }
  53348. if (url.indexOf(".wav", url.length - 4) !== -1) {
  53349. codecSupportedFound = true;
  53350. }
  53351. if (url.indexOf("blob:") !== -1) {
  53352. codecSupportedFound = true;
  53353. }
  53354. if (codecSupportedFound) {
  53355. // Loading sound using XHR2
  53356. if (!this._streaming) {
  53357. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  53358. }
  53359. else {
  53360. this._htmlAudioElement = new Audio(url);
  53361. this._htmlAudioElement.controls = false;
  53362. this._htmlAudioElement.loop = this.loop;
  53363. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  53364. this._htmlAudioElement.preload = "auto";
  53365. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  53366. _this._isReadyToPlay = true;
  53367. if (_this.autoplay) {
  53368. _this.play();
  53369. }
  53370. if (_this._readyToPlayCallback) {
  53371. _this._readyToPlayCallback();
  53372. }
  53373. });
  53374. document.body.appendChild(this._htmlAudioElement);
  53375. }
  53376. break;
  53377. }
  53378. }
  53379. break;
  53380. default:
  53381. validParameter = false;
  53382. break;
  53383. }
  53384. if (!validParameter) {
  53385. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  53386. }
  53387. else {
  53388. if (!codecSupportedFound) {
  53389. this._isReadyToPlay = true;
  53390. // Simulating a ready to play event to avoid breaking code path
  53391. if (this._readyToPlayCallback) {
  53392. window.setTimeout(function () {
  53393. if (_this._readyToPlayCallback) {
  53394. _this._readyToPlayCallback();
  53395. }
  53396. }, 1000);
  53397. }
  53398. }
  53399. }
  53400. }
  53401. }
  53402. else {
  53403. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  53404. this._scene.mainSoundTrack.AddSound(this);
  53405. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  53406. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  53407. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  53408. }
  53409. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  53410. if (this._readyToPlayCallback) {
  53411. window.setTimeout(function () {
  53412. if (_this._readyToPlayCallback) {
  53413. _this._readyToPlayCallback();
  53414. }
  53415. }, 1000);
  53416. }
  53417. }
  53418. }
  53419. Sound.prototype.dispose = function () {
  53420. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  53421. if (this.isPlaying) {
  53422. this.stop();
  53423. }
  53424. this._isReadyToPlay = false;
  53425. if (this.soundTrackId === -1) {
  53426. this._scene.mainSoundTrack.RemoveSound(this);
  53427. }
  53428. else {
  53429. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  53430. }
  53431. if (this._soundGain) {
  53432. this._soundGain.disconnect();
  53433. this._soundGain = null;
  53434. }
  53435. if (this._soundPanner) {
  53436. this._soundPanner.disconnect();
  53437. this._soundPanner = null;
  53438. }
  53439. if (this._soundSource) {
  53440. this._soundSource.disconnect();
  53441. this._soundSource = null;
  53442. }
  53443. this._audioBuffer = null;
  53444. if (this._htmlAudioElement) {
  53445. this._htmlAudioElement.pause();
  53446. this._htmlAudioElement.src = "";
  53447. document.body.removeChild(this._htmlAudioElement);
  53448. }
  53449. if (this._connectedMesh && this._registerFunc) {
  53450. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53451. this._connectedMesh = null;
  53452. }
  53453. }
  53454. };
  53455. Sound.prototype.isReady = function () {
  53456. return this._isReadyToPlay;
  53457. };
  53458. Sound.prototype._soundLoaded = function (audioData) {
  53459. var _this = this;
  53460. if (!BABYLON.Engine.audioEngine.audioContext) {
  53461. return;
  53462. }
  53463. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  53464. _this._audioBuffer = buffer;
  53465. _this._isReadyToPlay = true;
  53466. if (_this.autoplay) {
  53467. _this.play();
  53468. }
  53469. if (_this._readyToPlayCallback) {
  53470. _this._readyToPlayCallback();
  53471. }
  53472. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  53473. };
  53474. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  53475. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53476. this._audioBuffer = audioBuffer;
  53477. this._isReadyToPlay = true;
  53478. }
  53479. };
  53480. Sound.prototype.updateOptions = function (options) {
  53481. if (options) {
  53482. this.loop = options.loop || this.loop;
  53483. this.maxDistance = options.maxDistance || this.maxDistance;
  53484. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  53485. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  53486. this.refDistance = options.refDistance || this.refDistance;
  53487. this.distanceModel = options.distanceModel || this.distanceModel;
  53488. this._playbackRate = options.playbackRate || this._playbackRate;
  53489. this._updateSpatialParameters();
  53490. if (this.isPlaying) {
  53491. if (this._streaming) {
  53492. this._htmlAudioElement.playbackRate = this._playbackRate;
  53493. }
  53494. else {
  53495. if (this._soundSource) {
  53496. this._soundSource.playbackRate.value = this._playbackRate;
  53497. }
  53498. }
  53499. }
  53500. }
  53501. };
  53502. Sound.prototype._createSpatialParameters = function () {
  53503. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53504. if (this._scene.headphone) {
  53505. this._panningModel = "HRTF";
  53506. }
  53507. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  53508. this._updateSpatialParameters();
  53509. this._soundPanner.connect(this._ouputAudioNode);
  53510. this._inputAudioNode = this._soundPanner;
  53511. }
  53512. };
  53513. Sound.prototype._updateSpatialParameters = function () {
  53514. if (this.spatialSound && this._soundPanner) {
  53515. if (this.useCustomAttenuation) {
  53516. // Tricks to disable in a way embedded Web Audio attenuation
  53517. this._soundPanner.distanceModel = "linear";
  53518. this._soundPanner.maxDistance = Number.MAX_VALUE;
  53519. this._soundPanner.refDistance = 1;
  53520. this._soundPanner.rolloffFactor = 1;
  53521. this._soundPanner.panningModel = this._panningModel;
  53522. }
  53523. else {
  53524. this._soundPanner.distanceModel = this.distanceModel;
  53525. this._soundPanner.maxDistance = this.maxDistance;
  53526. this._soundPanner.refDistance = this.refDistance;
  53527. this._soundPanner.rolloffFactor = this.rolloffFactor;
  53528. this._soundPanner.panningModel = this._panningModel;
  53529. }
  53530. }
  53531. };
  53532. Sound.prototype.switchPanningModelToHRTF = function () {
  53533. this._panningModel = "HRTF";
  53534. this._switchPanningModel();
  53535. };
  53536. Sound.prototype.switchPanningModelToEqualPower = function () {
  53537. this._panningModel = "equalpower";
  53538. this._switchPanningModel();
  53539. };
  53540. Sound.prototype._switchPanningModel = function () {
  53541. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53542. this._soundPanner.panningModel = this._panningModel;
  53543. }
  53544. };
  53545. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  53546. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53547. if (this._isOutputConnected) {
  53548. this._ouputAudioNode.disconnect();
  53549. }
  53550. this._ouputAudioNode.connect(soundTrackAudioNode);
  53551. this._isOutputConnected = true;
  53552. }
  53553. };
  53554. /**
  53555. * Transform this sound into a directional source
  53556. * @param coneInnerAngle Size of the inner cone in degree
  53557. * @param coneOuterAngle Size of the outer cone in degree
  53558. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  53559. */
  53560. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  53561. if (coneOuterAngle < coneInnerAngle) {
  53562. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  53563. return;
  53564. }
  53565. this._coneInnerAngle = coneInnerAngle;
  53566. this._coneOuterAngle = coneOuterAngle;
  53567. this._coneOuterGain = coneOuterGain;
  53568. this._isDirectional = true;
  53569. if (this.isPlaying && this.loop) {
  53570. this.stop();
  53571. this.play();
  53572. }
  53573. };
  53574. Sound.prototype.setPosition = function (newPosition) {
  53575. this._position = newPosition;
  53576. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53577. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53578. }
  53579. };
  53580. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  53581. this._localDirection = newLocalDirection;
  53582. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  53583. this._updateDirection();
  53584. }
  53585. };
  53586. Sound.prototype._updateDirection = function () {
  53587. if (!this._connectedMesh || !this._soundPanner) {
  53588. return;
  53589. }
  53590. var mat = this._connectedMesh.getWorldMatrix();
  53591. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  53592. direction.normalize();
  53593. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  53594. };
  53595. Sound.prototype.updateDistanceFromListener = function () {
  53596. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  53597. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  53598. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  53599. }
  53600. };
  53601. Sound.prototype.setAttenuationFunction = function (callback) {
  53602. this._customAttenuationFunction = callback;
  53603. };
  53604. /**
  53605. * Play the sound
  53606. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  53607. * @param offset (optional) Start the sound setting it at a specific time
  53608. */
  53609. Sound.prototype.play = function (time, offset) {
  53610. var _this = this;
  53611. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  53612. try {
  53613. if (this._startOffset < 0) {
  53614. time = -this._startOffset;
  53615. this._startOffset = 0;
  53616. }
  53617. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53618. if (!this._soundSource || !this._streamingSource) {
  53619. if (this.spatialSound && this._soundPanner) {
  53620. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53621. if (this._isDirectional) {
  53622. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  53623. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  53624. this._soundPanner.coneOuterGain = this._coneOuterGain;
  53625. if (this._connectedMesh) {
  53626. this._updateDirection();
  53627. }
  53628. else {
  53629. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  53630. }
  53631. }
  53632. }
  53633. }
  53634. if (this._streaming) {
  53635. if (!this._streamingSource) {
  53636. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  53637. this._htmlAudioElement.onended = function () { _this._onended(); };
  53638. this._htmlAudioElement.playbackRate = this._playbackRate;
  53639. }
  53640. this._streamingSource.disconnect();
  53641. this._streamingSource.connect(this._inputAudioNode);
  53642. this._htmlAudioElement.play();
  53643. }
  53644. else {
  53645. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  53646. this._soundSource.buffer = this._audioBuffer;
  53647. this._soundSource.connect(this._inputAudioNode);
  53648. this._soundSource.loop = this.loop;
  53649. this._soundSource.playbackRate.value = this._playbackRate;
  53650. this._soundSource.onended = function () { _this._onended(); };
  53651. if (this._soundSource.buffer) {
  53652. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  53653. }
  53654. }
  53655. this._startTime = startTime;
  53656. this.isPlaying = true;
  53657. this.isPaused = false;
  53658. }
  53659. catch (ex) {
  53660. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  53661. }
  53662. }
  53663. };
  53664. Sound.prototype._onended = function () {
  53665. this.isPlaying = false;
  53666. if (this.onended) {
  53667. this.onended();
  53668. }
  53669. };
  53670. /**
  53671. * Stop the sound
  53672. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  53673. */
  53674. Sound.prototype.stop = function (time) {
  53675. if (this.isPlaying) {
  53676. if (this._streaming) {
  53677. this._htmlAudioElement.pause();
  53678. // Test needed for Firefox or it will generate an Invalid State Error
  53679. if (this._htmlAudioElement.currentTime > 0) {
  53680. this._htmlAudioElement.currentTime = 0;
  53681. }
  53682. }
  53683. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53684. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53685. this._soundSource.stop(stopTime);
  53686. this._soundSource.onended = function () { };
  53687. if (!this.isPaused) {
  53688. this._startOffset = 0;
  53689. }
  53690. }
  53691. this.isPlaying = false;
  53692. }
  53693. };
  53694. Sound.prototype.pause = function () {
  53695. if (this.isPlaying) {
  53696. this.isPaused = true;
  53697. if (this._streaming) {
  53698. this._htmlAudioElement.pause();
  53699. }
  53700. else if (BABYLON.Engine.audioEngine.audioContext) {
  53701. this.stop(0);
  53702. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53703. }
  53704. }
  53705. };
  53706. Sound.prototype.setVolume = function (newVolume, time) {
  53707. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53708. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53709. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53710. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53711. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53712. }
  53713. else {
  53714. this._soundGain.gain.value = newVolume;
  53715. }
  53716. }
  53717. this._volume = newVolume;
  53718. };
  53719. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53720. this._playbackRate = newPlaybackRate;
  53721. if (this.isPlaying) {
  53722. if (this._streaming) {
  53723. this._htmlAudioElement.playbackRate = this._playbackRate;
  53724. }
  53725. else if (this._soundSource) {
  53726. this._soundSource.playbackRate.value = this._playbackRate;
  53727. }
  53728. }
  53729. };
  53730. Sound.prototype.getVolume = function () {
  53731. return this._volume;
  53732. };
  53733. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53734. var _this = this;
  53735. if (this._connectedMesh && this._registerFunc) {
  53736. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53737. this._registerFunc = null;
  53738. }
  53739. this._connectedMesh = meshToConnectTo;
  53740. if (!this.spatialSound) {
  53741. this.spatialSound = true;
  53742. this._createSpatialParameters();
  53743. if (this.isPlaying && this.loop) {
  53744. this.stop();
  53745. this.play();
  53746. }
  53747. }
  53748. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53749. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53750. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53751. };
  53752. Sound.prototype.detachFromMesh = function () {
  53753. if (this._connectedMesh && this._registerFunc) {
  53754. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53755. this._registerFunc = null;
  53756. this._connectedMesh = null;
  53757. }
  53758. };
  53759. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53760. if (!node.getBoundingInfo) {
  53761. return;
  53762. }
  53763. var mesh = node;
  53764. var boundingInfo = mesh.getBoundingInfo();
  53765. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53766. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53767. this._updateDirection();
  53768. }
  53769. };
  53770. Sound.prototype.clone = function () {
  53771. var _this = this;
  53772. if (!this._streaming) {
  53773. var setBufferAndRun = function () {
  53774. if (_this._isReadyToPlay) {
  53775. clonedSound._audioBuffer = _this.getAudioBuffer();
  53776. clonedSound._isReadyToPlay = true;
  53777. if (clonedSound.autoplay) {
  53778. clonedSound.play();
  53779. }
  53780. }
  53781. else {
  53782. window.setTimeout(setBufferAndRun, 300);
  53783. }
  53784. };
  53785. var currentOptions = {
  53786. autoplay: this.autoplay, loop: this.loop,
  53787. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  53788. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  53789. refDistance: this.refDistance, distanceModel: this.distanceModel
  53790. };
  53791. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  53792. if (this.useCustomAttenuation) {
  53793. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  53794. }
  53795. clonedSound.setPosition(this._position);
  53796. clonedSound.setPlaybackRate(this._playbackRate);
  53797. setBufferAndRun();
  53798. return clonedSound;
  53799. }
  53800. else {
  53801. return null;
  53802. }
  53803. };
  53804. Sound.prototype.getAudioBuffer = function () {
  53805. return this._audioBuffer;
  53806. };
  53807. Sound.prototype.serialize = function () {
  53808. var serializationObject = {
  53809. name: this.name,
  53810. url: this.name,
  53811. autoplay: this.autoplay,
  53812. loop: this.loop,
  53813. volume: this._volume,
  53814. spatialSound: this.spatialSound,
  53815. maxDistance: this.maxDistance,
  53816. rolloffFactor: this.rolloffFactor,
  53817. refDistance: this.refDistance,
  53818. distanceModel: this.distanceModel,
  53819. playbackRate: this._playbackRate,
  53820. panningModel: this._panningModel,
  53821. soundTrackId: this.soundTrackId
  53822. };
  53823. if (this.spatialSound) {
  53824. if (this._connectedMesh)
  53825. serializationObject.connectedMeshId = this._connectedMesh.id;
  53826. serializationObject.position = this._position.asArray();
  53827. serializationObject.refDistance = this.refDistance;
  53828. serializationObject.distanceModel = this.distanceModel;
  53829. serializationObject.isDirectional = this._isDirectional;
  53830. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  53831. serializationObject.coneInnerAngle = this._coneInnerAngle;
  53832. serializationObject.coneOuterAngle = this._coneOuterAngle;
  53833. serializationObject.coneOuterGain = this._coneOuterGain;
  53834. }
  53835. return serializationObject;
  53836. };
  53837. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  53838. var soundName = parsedSound.name;
  53839. var soundUrl;
  53840. if (parsedSound.url) {
  53841. soundUrl = rootUrl + parsedSound.url;
  53842. }
  53843. else {
  53844. soundUrl = rootUrl + soundName;
  53845. }
  53846. var options = {
  53847. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  53848. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  53849. rolloffFactor: parsedSound.rolloffFactor,
  53850. refDistance: parsedSound.refDistance,
  53851. distanceModel: parsedSound.distanceModel,
  53852. playbackRate: parsedSound.playbackRate
  53853. };
  53854. var newSound;
  53855. if (!sourceSound) {
  53856. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  53857. scene._addPendingData(newSound);
  53858. }
  53859. else {
  53860. var setBufferAndRun = function () {
  53861. if (sourceSound._isReadyToPlay) {
  53862. newSound._audioBuffer = sourceSound.getAudioBuffer();
  53863. newSound._isReadyToPlay = true;
  53864. if (newSound.autoplay) {
  53865. newSound.play();
  53866. }
  53867. }
  53868. else {
  53869. window.setTimeout(setBufferAndRun, 300);
  53870. }
  53871. };
  53872. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  53873. setBufferAndRun();
  53874. }
  53875. if (parsedSound.position) {
  53876. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  53877. newSound.setPosition(soundPosition);
  53878. }
  53879. if (parsedSound.isDirectional) {
  53880. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  53881. if (parsedSound.localDirectionToMesh) {
  53882. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  53883. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  53884. }
  53885. }
  53886. if (parsedSound.connectedMeshId) {
  53887. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  53888. if (connectedMesh) {
  53889. newSound.attachToMesh(connectedMesh);
  53890. }
  53891. }
  53892. return newSound;
  53893. };
  53894. return Sound;
  53895. }());
  53896. BABYLON.Sound = Sound;
  53897. })(BABYLON || (BABYLON = {}));
  53898. //# sourceMappingURL=babylon.sound.js.map
  53899. var BABYLON;
  53900. (function (BABYLON) {
  53901. var SoundTrack = /** @class */ (function () {
  53902. function SoundTrack(scene, options) {
  53903. this.id = -1;
  53904. this._isMainTrack = false;
  53905. this._isInitialized = false;
  53906. this._scene = scene;
  53907. this.soundCollection = new Array();
  53908. this._options = options;
  53909. if (!this._isMainTrack) {
  53910. this._scene.soundTracks.push(this);
  53911. this.id = this._scene.soundTracks.length - 1;
  53912. }
  53913. }
  53914. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  53915. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53916. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  53917. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  53918. if (this._options) {
  53919. if (this._options.volume) {
  53920. this._outputAudioNode.gain.value = this._options.volume;
  53921. }
  53922. if (this._options.mainTrack) {
  53923. this._isMainTrack = this._options.mainTrack;
  53924. }
  53925. }
  53926. this._isInitialized = true;
  53927. }
  53928. };
  53929. SoundTrack.prototype.dispose = function () {
  53930. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53931. if (this._connectedAnalyser) {
  53932. this._connectedAnalyser.stopDebugCanvas();
  53933. }
  53934. while (this.soundCollection.length) {
  53935. this.soundCollection[0].dispose();
  53936. }
  53937. if (this._outputAudioNode) {
  53938. this._outputAudioNode.disconnect();
  53939. }
  53940. this._outputAudioNode = null;
  53941. }
  53942. };
  53943. SoundTrack.prototype.AddSound = function (sound) {
  53944. if (!this._isInitialized) {
  53945. this._initializeSoundTrackAudioGraph();
  53946. }
  53947. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53948. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  53949. }
  53950. if (sound.soundTrackId) {
  53951. if (sound.soundTrackId === -1) {
  53952. this._scene.mainSoundTrack.RemoveSound(sound);
  53953. }
  53954. else {
  53955. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  53956. }
  53957. }
  53958. this.soundCollection.push(sound);
  53959. sound.soundTrackId = this.id;
  53960. };
  53961. SoundTrack.prototype.RemoveSound = function (sound) {
  53962. var index = this.soundCollection.indexOf(sound);
  53963. if (index !== -1) {
  53964. this.soundCollection.splice(index, 1);
  53965. }
  53966. };
  53967. SoundTrack.prototype.setVolume = function (newVolume) {
  53968. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53969. this._outputAudioNode.gain.value = newVolume;
  53970. }
  53971. };
  53972. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  53973. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53974. for (var i = 0; i < this.soundCollection.length; i++) {
  53975. this.soundCollection[i].switchPanningModelToHRTF();
  53976. }
  53977. }
  53978. };
  53979. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  53980. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53981. for (var i = 0; i < this.soundCollection.length; i++) {
  53982. this.soundCollection[i].switchPanningModelToEqualPower();
  53983. }
  53984. }
  53985. };
  53986. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  53987. if (this._connectedAnalyser) {
  53988. this._connectedAnalyser.stopDebugCanvas();
  53989. }
  53990. this._connectedAnalyser = analyser;
  53991. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53992. this._outputAudioNode.disconnect();
  53993. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  53994. }
  53995. };
  53996. return SoundTrack;
  53997. }());
  53998. BABYLON.SoundTrack = SoundTrack;
  53999. })(BABYLON || (BABYLON = {}));
  54000. //# sourceMappingURL=babylon.soundtrack.js.map
  54001. var BABYLON;
  54002. (function (BABYLON) {
  54003. var Analyser = /** @class */ (function () {
  54004. function Analyser(scene) {
  54005. this.SMOOTHING = 0.75;
  54006. this.FFT_SIZE = 512;
  54007. this.BARGRAPHAMPLITUDE = 256;
  54008. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54009. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54010. this._scene = scene;
  54011. this._audioEngine = BABYLON.Engine.audioEngine;
  54012. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  54013. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54014. this._webAudioAnalyser.minDecibels = -140;
  54015. this._webAudioAnalyser.maxDecibels = 0;
  54016. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54017. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54018. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54019. }
  54020. }
  54021. Analyser.prototype.getFrequencyBinCount = function () {
  54022. if (this._audioEngine.canUseWebAudio) {
  54023. return this._webAudioAnalyser.frequencyBinCount;
  54024. }
  54025. else {
  54026. return 0;
  54027. }
  54028. };
  54029. Analyser.prototype.getByteFrequencyData = function () {
  54030. if (this._audioEngine.canUseWebAudio) {
  54031. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54032. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54033. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54034. }
  54035. return this._byteFreqs;
  54036. };
  54037. Analyser.prototype.getByteTimeDomainData = function () {
  54038. if (this._audioEngine.canUseWebAudio) {
  54039. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54040. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54041. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54042. }
  54043. return this._byteTime;
  54044. };
  54045. Analyser.prototype.getFloatFrequencyData = function () {
  54046. if (this._audioEngine.canUseWebAudio) {
  54047. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54048. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54049. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54050. }
  54051. return this._floatFreqs;
  54052. };
  54053. Analyser.prototype.drawDebugCanvas = function () {
  54054. var _this = this;
  54055. if (this._audioEngine.canUseWebAudio) {
  54056. if (!this._debugCanvas) {
  54057. this._debugCanvas = document.createElement("canvas");
  54058. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54059. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54060. this._debugCanvas.style.position = "absolute";
  54061. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54062. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54063. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54064. document.body.appendChild(this._debugCanvas);
  54065. this._registerFunc = function () {
  54066. _this.drawDebugCanvas();
  54067. };
  54068. this._scene.registerBeforeRender(this._registerFunc);
  54069. }
  54070. if (this._registerFunc && this._debugCanvasContext) {
  54071. var workingArray = this.getByteFrequencyData();
  54072. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54073. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54074. // Draw the frequency domain chart.
  54075. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54076. var value = workingArray[i];
  54077. var percent = value / this.BARGRAPHAMPLITUDE;
  54078. var height = this.DEBUGCANVASSIZE.height * percent;
  54079. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54080. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54081. var hue = i / this.getFrequencyBinCount() * 360;
  54082. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54083. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54084. }
  54085. }
  54086. }
  54087. };
  54088. Analyser.prototype.stopDebugCanvas = function () {
  54089. if (this._debugCanvas) {
  54090. if (this._registerFunc) {
  54091. this._scene.unregisterBeforeRender(this._registerFunc);
  54092. this._registerFunc = null;
  54093. }
  54094. document.body.removeChild(this._debugCanvas);
  54095. this._debugCanvas = null;
  54096. this._debugCanvasContext = null;
  54097. }
  54098. };
  54099. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54100. if (this._audioEngine.canUseWebAudio) {
  54101. inputAudioNode.connect(this._webAudioAnalyser);
  54102. this._webAudioAnalyser.connect(outputAudioNode);
  54103. }
  54104. };
  54105. Analyser.prototype.dispose = function () {
  54106. if (this._audioEngine.canUseWebAudio) {
  54107. this._webAudioAnalyser.disconnect();
  54108. }
  54109. };
  54110. return Analyser;
  54111. }());
  54112. BABYLON.Analyser = Analyser;
  54113. })(BABYLON || (BABYLON = {}));
  54114. //# sourceMappingURL=babylon.analyser.js.map
  54115. var BABYLON;
  54116. (function (BABYLON) {
  54117. var CubeTexture = /** @class */ (function (_super) {
  54118. __extends(CubeTexture, _super);
  54119. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  54120. if (extensions === void 0) { extensions = null; }
  54121. if (noMipmap === void 0) { noMipmap = false; }
  54122. if (files === void 0) { files = null; }
  54123. if (onLoad === void 0) { onLoad = null; }
  54124. if (onError === void 0) { onError = null; }
  54125. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54126. if (prefiltered === void 0) { prefiltered = false; }
  54127. if (forcedExtension === void 0) { forcedExtension = null; }
  54128. var _this = _super.call(this, scene) || this;
  54129. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54130. _this.name = rootUrl;
  54131. _this.url = rootUrl;
  54132. _this._noMipmap = noMipmap;
  54133. _this.hasAlpha = false;
  54134. _this._format = format;
  54135. _this._prefiltered = prefiltered;
  54136. _this.isCube = true;
  54137. _this._textureMatrix = BABYLON.Matrix.Identity();
  54138. if (prefiltered) {
  54139. _this.gammaSpace = false;
  54140. }
  54141. if (!rootUrl && !files) {
  54142. return _this;
  54143. }
  54144. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  54145. var lastDot = rootUrl.lastIndexOf(".");
  54146. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  54147. var isDDS = (extension === ".dds");
  54148. if (!files) {
  54149. if (!isDDS && !extensions) {
  54150. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  54151. }
  54152. files = [];
  54153. if (extensions) {
  54154. for (var index = 0; index < extensions.length; index++) {
  54155. files.push(rootUrl + extensions[index]);
  54156. }
  54157. }
  54158. }
  54159. _this._files = files;
  54160. if (!_this._texture) {
  54161. if (!scene.useDelayedTextureLoading) {
  54162. if (prefiltered) {
  54163. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  54164. }
  54165. else {
  54166. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  54167. }
  54168. }
  54169. else {
  54170. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54171. }
  54172. }
  54173. else if (onLoad) {
  54174. if (_this._texture.isReady) {
  54175. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  54176. }
  54177. else {
  54178. _this._texture.onLoadedObservable.add(onLoad);
  54179. }
  54180. }
  54181. return _this;
  54182. }
  54183. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  54184. return new CubeTexture("", scene, null, noMipmap, files);
  54185. };
  54186. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  54187. if (forcedExtension === void 0) { forcedExtension = null; }
  54188. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  54189. };
  54190. // Methods
  54191. CubeTexture.prototype.delayLoad = function () {
  54192. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54193. return;
  54194. }
  54195. var scene = this.getScene();
  54196. if (!scene) {
  54197. return;
  54198. }
  54199. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54200. this._texture = this._getFromCache(this.url, this._noMipmap);
  54201. if (!this._texture) {
  54202. if (this._prefiltered) {
  54203. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  54204. }
  54205. else {
  54206. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  54207. }
  54208. }
  54209. };
  54210. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  54211. return this._textureMatrix;
  54212. };
  54213. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  54214. this._textureMatrix = value;
  54215. };
  54216. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54217. var texture = BABYLON.SerializationHelper.Parse(function () {
  54218. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  54219. }, parsedTexture, scene);
  54220. // Animations
  54221. if (parsedTexture.animations) {
  54222. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  54223. var parsedAnimation = parsedTexture.animations[animationIndex];
  54224. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54225. }
  54226. }
  54227. return texture;
  54228. };
  54229. CubeTexture.prototype.clone = function () {
  54230. var _this = this;
  54231. return BABYLON.SerializationHelper.Clone(function () {
  54232. var scene = _this.getScene();
  54233. if (!scene) {
  54234. return _this;
  54235. }
  54236. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  54237. }, this);
  54238. };
  54239. return CubeTexture;
  54240. }(BABYLON.BaseTexture));
  54241. BABYLON.CubeTexture = CubeTexture;
  54242. })(BABYLON || (BABYLON = {}));
  54243. //# sourceMappingURL=babylon.cubeTexture.js.map
  54244. var BABYLON;
  54245. (function (BABYLON) {
  54246. var RenderTargetTexture = /** @class */ (function (_super) {
  54247. __extends(RenderTargetTexture, _super);
  54248. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  54249. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  54250. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54251. if (isCube === void 0) { isCube = false; }
  54252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54253. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54254. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  54255. if (isMulti === void 0) { isMulti = false; }
  54256. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54257. _this.isCube = isCube;
  54258. /**
  54259. * Use this list to define the list of mesh you want to render.
  54260. */
  54261. _this.renderList = new Array();
  54262. _this.renderParticles = true;
  54263. _this.renderSprites = false;
  54264. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  54265. _this.ignoreCameraViewport = false;
  54266. // Events
  54267. /**
  54268. * An event triggered when the texture is unbind.
  54269. * @type {BABYLON.Observable}
  54270. */
  54271. _this.onBeforeBindObservable = new BABYLON.Observable();
  54272. /**
  54273. * An event triggered when the texture is unbind.
  54274. * @type {BABYLON.Observable}
  54275. */
  54276. _this.onAfterUnbindObservable = new BABYLON.Observable();
  54277. /**
  54278. * An event triggered before rendering the texture
  54279. * @type {BABYLON.Observable}
  54280. */
  54281. _this.onBeforeRenderObservable = new BABYLON.Observable();
  54282. /**
  54283. * An event triggered after rendering the texture
  54284. * @type {BABYLON.Observable}
  54285. */
  54286. _this.onAfterRenderObservable = new BABYLON.Observable();
  54287. /**
  54288. * An event triggered after the texture clear
  54289. * @type {BABYLON.Observable}
  54290. */
  54291. _this.onClearObservable = new BABYLON.Observable();
  54292. _this._currentRefreshId = -1;
  54293. _this._refreshRate = 1;
  54294. _this._samples = 1;
  54295. scene = _this.getScene();
  54296. if (!scene) {
  54297. return _this;
  54298. }
  54299. _this._engine = scene.getEngine();
  54300. _this.name = name;
  54301. _this.isRenderTarget = true;
  54302. _this._initialSizeParameter = size;
  54303. _this._processSizeParameter(size);
  54304. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  54305. });
  54306. _this._generateMipMaps = generateMipMaps ? true : false;
  54307. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  54308. // Rendering groups
  54309. _this._renderingManager = new BABYLON.RenderingManager(scene);
  54310. if (isMulti) {
  54311. return _this;
  54312. }
  54313. _this._renderTargetOptions = {
  54314. generateMipMaps: generateMipMaps,
  54315. type: type,
  54316. samplingMode: samplingMode,
  54317. generateDepthBuffer: generateDepthBuffer,
  54318. generateStencilBuffer: generateStencilBuffer
  54319. };
  54320. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  54321. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54322. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54323. }
  54324. if (isCube) {
  54325. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  54326. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  54327. _this._textureMatrix = BABYLON.Matrix.Identity();
  54328. }
  54329. else {
  54330. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  54331. }
  54332. return _this;
  54333. }
  54334. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  54335. get: function () {
  54336. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  54337. },
  54338. enumerable: true,
  54339. configurable: true
  54340. });
  54341. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  54342. get: function () {
  54343. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  54344. },
  54345. enumerable: true,
  54346. configurable: true
  54347. });
  54348. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  54349. get: function () {
  54350. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  54351. },
  54352. enumerable: true,
  54353. configurable: true
  54354. });
  54355. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  54356. set: function (callback) {
  54357. if (this._onAfterUnbindObserver) {
  54358. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  54359. }
  54360. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  54361. },
  54362. enumerable: true,
  54363. configurable: true
  54364. });
  54365. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  54366. set: function (callback) {
  54367. if (this._onBeforeRenderObserver) {
  54368. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54369. }
  54370. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54371. },
  54372. enumerable: true,
  54373. configurable: true
  54374. });
  54375. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  54376. set: function (callback) {
  54377. if (this._onAfterRenderObserver) {
  54378. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54379. }
  54380. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54381. },
  54382. enumerable: true,
  54383. configurable: true
  54384. });
  54385. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  54386. set: function (callback) {
  54387. if (this._onClearObserver) {
  54388. this.onClearObservable.remove(this._onClearObserver);
  54389. }
  54390. this._onClearObserver = this.onClearObservable.add(callback);
  54391. },
  54392. enumerable: true,
  54393. configurable: true
  54394. });
  54395. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  54396. get: function () {
  54397. return this._renderTargetOptions;
  54398. },
  54399. enumerable: true,
  54400. configurable: true
  54401. });
  54402. RenderTargetTexture.prototype._onRatioRescale = function () {
  54403. if (this._sizeRatio) {
  54404. this.resize(this._initialSizeParameter);
  54405. }
  54406. };
  54407. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  54408. if (size.ratio) {
  54409. this._sizeRatio = size.ratio;
  54410. this._size = {
  54411. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  54412. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  54413. };
  54414. }
  54415. else {
  54416. this._size = size;
  54417. }
  54418. };
  54419. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  54420. get: function () {
  54421. return this._samples;
  54422. },
  54423. set: function (value) {
  54424. if (this._samples === value) {
  54425. return;
  54426. }
  54427. var scene = this.getScene();
  54428. if (!scene) {
  54429. return;
  54430. }
  54431. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  54432. },
  54433. enumerable: true,
  54434. configurable: true
  54435. });
  54436. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  54437. this._currentRefreshId = -1;
  54438. };
  54439. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  54440. get: function () {
  54441. return this._refreshRate;
  54442. },
  54443. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54444. set: function (value) {
  54445. this._refreshRate = value;
  54446. this.resetRefreshCounter();
  54447. },
  54448. enumerable: true,
  54449. configurable: true
  54450. });
  54451. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  54452. if (!this._postProcessManager) {
  54453. var scene = this.getScene();
  54454. if (!scene) {
  54455. return;
  54456. }
  54457. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  54458. this._postProcesses = new Array();
  54459. }
  54460. this._postProcesses.push(postProcess);
  54461. this._postProcesses[0].autoClear = false;
  54462. };
  54463. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  54464. if (!this._postProcesses) {
  54465. return;
  54466. }
  54467. if (dispose) {
  54468. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  54469. var postProcess = _a[_i];
  54470. postProcess.dispose();
  54471. }
  54472. }
  54473. this._postProcesses = [];
  54474. };
  54475. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  54476. if (!this._postProcesses) {
  54477. return;
  54478. }
  54479. var index = this._postProcesses.indexOf(postProcess);
  54480. if (index === -1) {
  54481. return;
  54482. }
  54483. this._postProcesses.splice(index, 1);
  54484. if (this._postProcesses.length > 0) {
  54485. this._postProcesses[0].autoClear = false;
  54486. }
  54487. };
  54488. RenderTargetTexture.prototype._shouldRender = function () {
  54489. if (this._currentRefreshId === -1) {
  54490. this._currentRefreshId = 1;
  54491. return true;
  54492. }
  54493. if (this.refreshRate === this._currentRefreshId) {
  54494. this._currentRefreshId = 1;
  54495. return true;
  54496. }
  54497. this._currentRefreshId++;
  54498. return false;
  54499. };
  54500. RenderTargetTexture.prototype.getRenderSize = function () {
  54501. if (this._size.width) {
  54502. return this._size.width;
  54503. }
  54504. return this._size;
  54505. };
  54506. RenderTargetTexture.prototype.getRenderWidth = function () {
  54507. if (this._size.width) {
  54508. return this._size.width;
  54509. }
  54510. return this._size;
  54511. };
  54512. RenderTargetTexture.prototype.getRenderHeight = function () {
  54513. if (this._size.width) {
  54514. return this._size.height;
  54515. }
  54516. return this._size;
  54517. };
  54518. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  54519. get: function () {
  54520. return true;
  54521. },
  54522. enumerable: true,
  54523. configurable: true
  54524. });
  54525. RenderTargetTexture.prototype.scale = function (ratio) {
  54526. var newSize = this.getRenderSize() * ratio;
  54527. this.resize(newSize);
  54528. };
  54529. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  54530. if (this.isCube) {
  54531. return this._textureMatrix;
  54532. }
  54533. return _super.prototype.getReflectionTextureMatrix.call(this);
  54534. };
  54535. RenderTargetTexture.prototype.resize = function (size) {
  54536. this.releaseInternalTexture();
  54537. var scene = this.getScene();
  54538. if (!scene) {
  54539. return;
  54540. }
  54541. this._processSizeParameter(size);
  54542. if (this.isCube) {
  54543. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  54544. }
  54545. else {
  54546. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  54547. }
  54548. };
  54549. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  54550. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  54551. if (dumpForDebug === void 0) { dumpForDebug = false; }
  54552. var scene = this.getScene();
  54553. if (!scene) {
  54554. return;
  54555. }
  54556. var engine = scene.getEngine();
  54557. if (this.useCameraPostProcesses !== undefined) {
  54558. useCameraPostProcess = this.useCameraPostProcesses;
  54559. }
  54560. if (this._waitingRenderList) {
  54561. this.renderList = [];
  54562. for (var index = 0; index < this._waitingRenderList.length; index++) {
  54563. var id = this._waitingRenderList[index];
  54564. var mesh_1 = scene.getMeshByID(id);
  54565. if (mesh_1) {
  54566. this.renderList.push(mesh_1);
  54567. }
  54568. }
  54569. delete this._waitingRenderList;
  54570. }
  54571. // Is predicate defined?
  54572. if (this.renderListPredicate) {
  54573. if (this.renderList) {
  54574. this.renderList.splice(0); // Clear previous renderList
  54575. }
  54576. else {
  54577. this.renderList = [];
  54578. }
  54579. var scene = this.getScene();
  54580. if (!scene) {
  54581. return;
  54582. }
  54583. var sceneMeshes = scene.meshes;
  54584. for (var index = 0; index < sceneMeshes.length; index++) {
  54585. var mesh = sceneMeshes[index];
  54586. if (this.renderListPredicate(mesh)) {
  54587. this.renderList.push(mesh);
  54588. }
  54589. }
  54590. }
  54591. this.onBeforeBindObservable.notifyObservers(this);
  54592. // Set custom projection.
  54593. // Needs to be before binding to prevent changing the aspect ratio.
  54594. var camera;
  54595. if (this.activeCamera) {
  54596. camera = this.activeCamera;
  54597. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54598. if (this.activeCamera !== scene.activeCamera) {
  54599. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  54600. }
  54601. }
  54602. else {
  54603. camera = scene.activeCamera;
  54604. if (camera) {
  54605. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54606. }
  54607. }
  54608. // Prepare renderingManager
  54609. this._renderingManager.reset();
  54610. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  54611. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  54612. var sceneRenderId = scene.getRenderId();
  54613. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  54614. var mesh = currentRenderList[meshIndex];
  54615. if (mesh) {
  54616. if (!mesh.isReady()) {
  54617. // Reset _currentRefreshId
  54618. this.resetRefreshCounter();
  54619. continue;
  54620. }
  54621. mesh._preActivateForIntermediateRendering(sceneRenderId);
  54622. var isMasked = void 0;
  54623. if (!this.renderList && camera) {
  54624. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  54625. }
  54626. else {
  54627. isMasked = false;
  54628. }
  54629. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  54630. mesh._activate(sceneRenderId);
  54631. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  54632. var subMesh = mesh.subMeshes[subIndex];
  54633. scene._activeIndices.addCount(subMesh.indexCount, false);
  54634. this._renderingManager.dispatch(subMesh, mesh);
  54635. }
  54636. }
  54637. }
  54638. }
  54639. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  54640. var particleSystem = scene.particleSystems[particleIndex];
  54641. var emitter = particleSystem.emitter;
  54642. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  54643. continue;
  54644. }
  54645. if (currentRenderList.indexOf(emitter) >= 0) {
  54646. this._renderingManager.dispatchParticles(particleSystem);
  54647. }
  54648. }
  54649. if (this.isCube) {
  54650. for (var face = 0; face < 6; face++) {
  54651. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54652. scene.incrementRenderId();
  54653. scene.resetCachedMaterial();
  54654. }
  54655. }
  54656. else {
  54657. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54658. }
  54659. this.onAfterUnbindObservable.notifyObservers(this);
  54660. if (scene.activeCamera) {
  54661. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  54662. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  54663. }
  54664. engine.setViewport(scene.activeCamera.viewport);
  54665. }
  54666. scene.resetCachedMaterial();
  54667. };
  54668. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  54669. var minimum = 128;
  54670. var x = renderDimension * scale;
  54671. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  54672. // Ensure we don't exceed the render dimension (while staying POT)
  54673. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  54674. };
  54675. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54676. var _this = this;
  54677. if (!this._texture) {
  54678. return;
  54679. }
  54680. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54681. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54682. });
  54683. };
  54684. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54685. var scene = this.getScene();
  54686. if (!scene) {
  54687. return;
  54688. }
  54689. var engine = scene.getEngine();
  54690. if (!this._texture) {
  54691. return;
  54692. }
  54693. // Bind
  54694. if (this._postProcessManager) {
  54695. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54696. }
  54697. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54698. if (this._texture) {
  54699. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54700. }
  54701. }
  54702. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54703. // Clear
  54704. if (this.onClearObservable.hasObservers()) {
  54705. this.onClearObservable.notifyObservers(engine);
  54706. }
  54707. else {
  54708. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54709. }
  54710. if (!this._doNotChangeAspectRatio) {
  54711. scene.updateTransformMatrix(true);
  54712. }
  54713. // Render
  54714. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54715. if (this._postProcessManager) {
  54716. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54717. }
  54718. else if (useCameraPostProcess) {
  54719. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54720. }
  54721. if (!this._doNotChangeAspectRatio) {
  54722. scene.updateTransformMatrix(true);
  54723. }
  54724. // Dump ?
  54725. if (dumpForDebug) {
  54726. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54727. }
  54728. // Unbind
  54729. if (!this.isCube || faceIndex === 5) {
  54730. if (this.isCube) {
  54731. if (faceIndex === 5) {
  54732. engine.generateMipMapsForCubemap(this._texture);
  54733. }
  54734. }
  54735. this.unbindFrameBuffer(engine, faceIndex);
  54736. }
  54737. else {
  54738. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54739. }
  54740. };
  54741. /**
  54742. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54743. * This allowed control for front to back rendering or reversly depending of the special needs.
  54744. *
  54745. * @param renderingGroupId The rendering group id corresponding to its index
  54746. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54747. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54748. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54749. */
  54750. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54751. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54752. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54753. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54754. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54755. };
  54756. /**
  54757. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54758. *
  54759. * @param renderingGroupId The rendering group id corresponding to its index
  54760. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54761. */
  54762. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54763. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54764. };
  54765. RenderTargetTexture.prototype.clone = function () {
  54766. var textureSize = this.getSize();
  54767. 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);
  54768. // Base texture
  54769. newTexture.hasAlpha = this.hasAlpha;
  54770. newTexture.level = this.level;
  54771. // RenderTarget Texture
  54772. newTexture.coordinatesMode = this.coordinatesMode;
  54773. if (this.renderList) {
  54774. newTexture.renderList = this.renderList.slice(0);
  54775. }
  54776. return newTexture;
  54777. };
  54778. RenderTargetTexture.prototype.serialize = function () {
  54779. if (!this.name) {
  54780. return null;
  54781. }
  54782. var serializationObject = _super.prototype.serialize.call(this);
  54783. serializationObject.renderTargetSize = this.getRenderSize();
  54784. serializationObject.renderList = [];
  54785. if (this.renderList) {
  54786. for (var index = 0; index < this.renderList.length; index++) {
  54787. serializationObject.renderList.push(this.renderList[index].id);
  54788. }
  54789. }
  54790. return serializationObject;
  54791. };
  54792. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  54793. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  54794. var objBuffer = this.getInternalTexture();
  54795. var scene = this.getScene();
  54796. if (objBuffer && scene) {
  54797. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  54798. }
  54799. };
  54800. RenderTargetTexture.prototype.dispose = function () {
  54801. if (this._postProcessManager) {
  54802. this._postProcessManager.dispose();
  54803. this._postProcessManager = null;
  54804. }
  54805. this.clearPostProcesses(true);
  54806. if (this._resizeObserver) {
  54807. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  54808. this._resizeObserver = null;
  54809. }
  54810. this.renderList = null;
  54811. // Remove from custom render targets
  54812. var scene = this.getScene();
  54813. if (!scene) {
  54814. return;
  54815. }
  54816. var index = scene.customRenderTargets.indexOf(this);
  54817. if (index >= 0) {
  54818. scene.customRenderTargets.splice(index, 1);
  54819. }
  54820. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  54821. var camera = _a[_i];
  54822. index = camera.customRenderTargets.indexOf(this);
  54823. if (index >= 0) {
  54824. camera.customRenderTargets.splice(index, 1);
  54825. }
  54826. }
  54827. _super.prototype.dispose.call(this);
  54828. };
  54829. RenderTargetTexture.prototype._rebuild = function () {
  54830. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54831. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54832. }
  54833. if (this._postProcessManager) {
  54834. this._postProcessManager._rebuild();
  54835. }
  54836. };
  54837. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  54838. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  54839. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  54840. return RenderTargetTexture;
  54841. }(BABYLON.Texture));
  54842. BABYLON.RenderTargetTexture = RenderTargetTexture;
  54843. })(BABYLON || (BABYLON = {}));
  54844. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  54845. var BABYLON;
  54846. (function (BABYLON) {
  54847. ;
  54848. var MultiRenderTarget = /** @class */ (function (_super) {
  54849. __extends(MultiRenderTarget, _super);
  54850. function MultiRenderTarget(name, size, count, scene, options) {
  54851. var _this = this;
  54852. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  54853. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  54854. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  54855. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  54856. _this._engine = scene.getEngine();
  54857. if (!_this.isSupported) {
  54858. _this.dispose();
  54859. return;
  54860. }
  54861. var types = [];
  54862. var samplingModes = [];
  54863. for (var i = 0; i < count; i++) {
  54864. if (options && options.types && options.types[i] !== undefined) {
  54865. types.push(options.types[i]);
  54866. }
  54867. else {
  54868. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54869. }
  54870. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  54871. samplingModes.push(options.samplingModes[i]);
  54872. }
  54873. else {
  54874. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54875. }
  54876. }
  54877. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  54878. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  54879. _this._size = size;
  54880. _this._multiRenderTargetOptions = {
  54881. samplingModes: samplingModes,
  54882. generateMipMaps: generateMipMaps,
  54883. generateDepthBuffer: generateDepthBuffer,
  54884. generateStencilBuffer: generateStencilBuffer,
  54885. generateDepthTexture: generateDepthTexture,
  54886. types: types,
  54887. textureCount: count
  54888. };
  54889. _this._createInternalTextures();
  54890. _this._createTextures();
  54891. return _this;
  54892. }
  54893. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  54894. get: function () {
  54895. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  54896. },
  54897. enumerable: true,
  54898. configurable: true
  54899. });
  54900. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  54901. get: function () {
  54902. return this._textures;
  54903. },
  54904. enumerable: true,
  54905. configurable: true
  54906. });
  54907. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  54908. get: function () {
  54909. return this._textures[this._textures.length - 1];
  54910. },
  54911. enumerable: true,
  54912. configurable: true
  54913. });
  54914. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  54915. set: function (wrap) {
  54916. if (this._textures) {
  54917. for (var i = 0; i < this._textures.length; i++) {
  54918. this._textures[i].wrapU = wrap;
  54919. }
  54920. }
  54921. },
  54922. enumerable: true,
  54923. configurable: true
  54924. });
  54925. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  54926. set: function (wrap) {
  54927. if (this._textures) {
  54928. for (var i = 0; i < this._textures.length; i++) {
  54929. this._textures[i].wrapV = wrap;
  54930. }
  54931. }
  54932. },
  54933. enumerable: true,
  54934. configurable: true
  54935. });
  54936. MultiRenderTarget.prototype._rebuild = function () {
  54937. this.releaseInternalTextures();
  54938. this._createInternalTextures();
  54939. for (var i = 0; i < this._internalTextures.length; i++) {
  54940. var texture = this._textures[i];
  54941. texture._texture = this._internalTextures[i];
  54942. }
  54943. // Keeps references to frame buffer and stencil/depth buffer
  54944. this._texture = this._internalTextures[0];
  54945. };
  54946. MultiRenderTarget.prototype._createInternalTextures = function () {
  54947. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  54948. };
  54949. MultiRenderTarget.prototype._createTextures = function () {
  54950. this._textures = [];
  54951. for (var i = 0; i < this._internalTextures.length; i++) {
  54952. var texture = new BABYLON.Texture(null, this.getScene());
  54953. texture._texture = this._internalTextures[i];
  54954. this._textures.push(texture);
  54955. }
  54956. // Keeps references to frame buffer and stencil/depth buffer
  54957. this._texture = this._internalTextures[0];
  54958. };
  54959. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  54960. get: function () {
  54961. return this._samples;
  54962. },
  54963. set: function (value) {
  54964. if (this._samples === value) {
  54965. return;
  54966. }
  54967. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  54968. },
  54969. enumerable: true,
  54970. configurable: true
  54971. });
  54972. MultiRenderTarget.prototype.resize = function (size) {
  54973. this.releaseInternalTextures();
  54974. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  54975. this._createInternalTextures();
  54976. };
  54977. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54978. var _this = this;
  54979. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  54980. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54981. });
  54982. };
  54983. MultiRenderTarget.prototype.dispose = function () {
  54984. this.releaseInternalTextures();
  54985. _super.prototype.dispose.call(this);
  54986. };
  54987. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  54988. if (!this._internalTextures) {
  54989. return;
  54990. }
  54991. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  54992. if (this._internalTextures[i] !== undefined) {
  54993. this._internalTextures[i].dispose();
  54994. this._internalTextures.splice(i, 1);
  54995. }
  54996. }
  54997. };
  54998. return MultiRenderTarget;
  54999. }(BABYLON.RenderTargetTexture));
  55000. BABYLON.MultiRenderTarget = MultiRenderTarget;
  55001. })(BABYLON || (BABYLON = {}));
  55002. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  55003. var BABYLON;
  55004. (function (BABYLON) {
  55005. var MirrorTexture = /** @class */ (function (_super) {
  55006. __extends(MirrorTexture, _super);
  55007. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  55008. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55009. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55010. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55011. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  55012. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  55013. _this._transformMatrix = BABYLON.Matrix.Zero();
  55014. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  55015. _this._adaptiveBlurKernel = 0;
  55016. _this._blurKernelX = 0;
  55017. _this._blurKernelY = 0;
  55018. _this._blurRatio = 1.0;
  55019. _this.ignoreCameraViewport = true;
  55020. _this.onBeforeRenderObservable.add(function () {
  55021. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  55022. _this._savedViewMatrix = scene.getViewMatrix();
  55023. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  55024. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  55025. scene.clipPlane = _this.mirrorPlane;
  55026. scene.getEngine().cullBackFaces = false;
  55027. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  55028. });
  55029. _this.onAfterRenderObservable.add(function () {
  55030. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  55031. scene.getEngine().cullBackFaces = true;
  55032. scene._mirroredCameraPosition = null;
  55033. delete scene.clipPlane;
  55034. });
  55035. return _this;
  55036. }
  55037. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  55038. get: function () {
  55039. return this._blurRatio;
  55040. },
  55041. set: function (value) {
  55042. if (this._blurRatio === value) {
  55043. return;
  55044. }
  55045. this._blurRatio = value;
  55046. this._preparePostProcesses();
  55047. },
  55048. enumerable: true,
  55049. configurable: true
  55050. });
  55051. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  55052. set: function (value) {
  55053. this._adaptiveBlurKernel = value;
  55054. this._autoComputeBlurKernel();
  55055. },
  55056. enumerable: true,
  55057. configurable: true
  55058. });
  55059. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  55060. set: function (value) {
  55061. this.blurKernelX = value;
  55062. this.blurKernelY = value;
  55063. },
  55064. enumerable: true,
  55065. configurable: true
  55066. });
  55067. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  55068. get: function () {
  55069. return this._blurKernelX;
  55070. },
  55071. set: function (value) {
  55072. if (this._blurKernelX === value) {
  55073. return;
  55074. }
  55075. this._blurKernelX = value;
  55076. this._preparePostProcesses();
  55077. },
  55078. enumerable: true,
  55079. configurable: true
  55080. });
  55081. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  55082. get: function () {
  55083. return this._blurKernelY;
  55084. },
  55085. set: function (value) {
  55086. if (this._blurKernelY === value) {
  55087. return;
  55088. }
  55089. this._blurKernelY = value;
  55090. this._preparePostProcesses();
  55091. },
  55092. enumerable: true,
  55093. configurable: true
  55094. });
  55095. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  55096. var engine = this.getScene().getEngine();
  55097. var dw = this.getRenderWidth() / engine.getRenderWidth();
  55098. var dh = this.getRenderHeight() / engine.getRenderHeight();
  55099. this.blurKernelX = this._adaptiveBlurKernel * dw;
  55100. this.blurKernelY = this._adaptiveBlurKernel * dh;
  55101. };
  55102. MirrorTexture.prototype._onRatioRescale = function () {
  55103. if (this._sizeRatio) {
  55104. this.resize(this._initialSizeParameter);
  55105. if (!this._adaptiveBlurKernel) {
  55106. this._preparePostProcesses();
  55107. }
  55108. }
  55109. if (this._adaptiveBlurKernel) {
  55110. this._autoComputeBlurKernel();
  55111. }
  55112. };
  55113. MirrorTexture.prototype._preparePostProcesses = function () {
  55114. this.clearPostProcesses(true);
  55115. if (this._blurKernelX && this._blurKernelY) {
  55116. var engine = this.getScene().getEngine();
  55117. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55118. 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);
  55119. this._blurX.autoClear = false;
  55120. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  55121. this._blurX.outputTexture = this._texture;
  55122. }
  55123. else {
  55124. this._blurX.alwaysForcePOT = true;
  55125. }
  55126. 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);
  55127. this._blurY.autoClear = false;
  55128. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  55129. this.addPostProcess(this._blurX);
  55130. this.addPostProcess(this._blurY);
  55131. }
  55132. else {
  55133. if (this._blurY) {
  55134. this.removePostProcess(this._blurY);
  55135. this._blurY.dispose();
  55136. this._blurY = null;
  55137. }
  55138. if (this._blurX) {
  55139. this.removePostProcess(this._blurX);
  55140. this._blurX.dispose();
  55141. this._blurX = null;
  55142. }
  55143. }
  55144. };
  55145. MirrorTexture.prototype.clone = function () {
  55146. var scene = this.getScene();
  55147. if (!scene) {
  55148. return this;
  55149. }
  55150. var textureSize = this.getSize();
  55151. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  55152. // Base texture
  55153. newTexture.hasAlpha = this.hasAlpha;
  55154. newTexture.level = this.level;
  55155. // Mirror Texture
  55156. newTexture.mirrorPlane = this.mirrorPlane.clone();
  55157. if (this.renderList) {
  55158. newTexture.renderList = this.renderList.slice(0);
  55159. }
  55160. return newTexture;
  55161. };
  55162. MirrorTexture.prototype.serialize = function () {
  55163. if (!this.name) {
  55164. return null;
  55165. }
  55166. var serializationObject = _super.prototype.serialize.call(this);
  55167. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  55168. return serializationObject;
  55169. };
  55170. return MirrorTexture;
  55171. }(BABYLON.RenderTargetTexture));
  55172. BABYLON.MirrorTexture = MirrorTexture;
  55173. })(BABYLON || (BABYLON = {}));
  55174. //# sourceMappingURL=babylon.mirrorTexture.js.map
  55175. var BABYLON;
  55176. (function (BABYLON) {
  55177. /**
  55178. * Creates a refraction texture used by refraction channel of the standard material.
  55179. * @param name the texture name
  55180. * @param size size of the underlying texture
  55181. * @param scene root scene
  55182. */
  55183. var RefractionTexture = /** @class */ (function (_super) {
  55184. __extends(RefractionTexture, _super);
  55185. function RefractionTexture(name, size, scene, generateMipMaps) {
  55186. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  55187. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  55188. _this.depth = 2.0;
  55189. _this.onBeforeRenderObservable.add(function () {
  55190. scene.clipPlane = _this.refractionPlane;
  55191. });
  55192. _this.onAfterRenderObservable.add(function () {
  55193. delete scene.clipPlane;
  55194. });
  55195. return _this;
  55196. }
  55197. RefractionTexture.prototype.clone = function () {
  55198. var scene = this.getScene();
  55199. if (!scene) {
  55200. return this;
  55201. }
  55202. var textureSize = this.getSize();
  55203. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  55204. // Base texture
  55205. newTexture.hasAlpha = this.hasAlpha;
  55206. newTexture.level = this.level;
  55207. // Refraction Texture
  55208. newTexture.refractionPlane = this.refractionPlane.clone();
  55209. if (this.renderList) {
  55210. newTexture.renderList = this.renderList.slice(0);
  55211. }
  55212. newTexture.depth = this.depth;
  55213. return newTexture;
  55214. };
  55215. RefractionTexture.prototype.serialize = function () {
  55216. if (!this.name) {
  55217. return null;
  55218. }
  55219. var serializationObject = _super.prototype.serialize.call(this);
  55220. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  55221. serializationObject.depth = this.depth;
  55222. return serializationObject;
  55223. };
  55224. return RefractionTexture;
  55225. }(BABYLON.RenderTargetTexture));
  55226. BABYLON.RefractionTexture = RefractionTexture;
  55227. })(BABYLON || (BABYLON = {}));
  55228. //# sourceMappingURL=babylon.refractionTexture.js.map
  55229. var BABYLON;
  55230. (function (BABYLON) {
  55231. var DynamicTexture = /** @class */ (function (_super) {
  55232. __extends(DynamicTexture, _super);
  55233. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  55234. if (scene === void 0) { scene = null; }
  55235. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55236. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55237. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  55238. _this.name = name;
  55239. _this._engine = _this.getScene().getEngine();
  55240. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55241. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55242. _this._generateMipMaps = generateMipMaps;
  55243. if (options.getContext) {
  55244. _this._canvas = options;
  55245. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55246. }
  55247. else {
  55248. _this._canvas = document.createElement("canvas");
  55249. if (options.width) {
  55250. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  55251. }
  55252. else {
  55253. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  55254. }
  55255. }
  55256. var textureSize = _this.getSize();
  55257. _this._canvas.width = textureSize.width;
  55258. _this._canvas.height = textureSize.height;
  55259. _this._context = _this._canvas.getContext("2d");
  55260. return _this;
  55261. }
  55262. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  55263. get: function () {
  55264. return true;
  55265. },
  55266. enumerable: true,
  55267. configurable: true
  55268. });
  55269. DynamicTexture.prototype._recreate = function (textureSize) {
  55270. this._canvas.width = textureSize.width;
  55271. this._canvas.height = textureSize.height;
  55272. this.releaseInternalTexture();
  55273. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  55274. };
  55275. DynamicTexture.prototype.scale = function (ratio) {
  55276. var textureSize = this.getSize();
  55277. textureSize.width *= ratio;
  55278. textureSize.height *= ratio;
  55279. this._recreate(textureSize);
  55280. };
  55281. DynamicTexture.prototype.scaleTo = function (width, height) {
  55282. var textureSize = this.getSize();
  55283. textureSize.width = width;
  55284. textureSize.height = height;
  55285. this._recreate(textureSize);
  55286. };
  55287. DynamicTexture.prototype.getContext = function () {
  55288. return this._context;
  55289. };
  55290. DynamicTexture.prototype.clear = function () {
  55291. var size = this.getSize();
  55292. this._context.fillRect(0, 0, size.width, size.height);
  55293. };
  55294. DynamicTexture.prototype.update = function (invertY) {
  55295. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  55296. };
  55297. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  55298. if (update === void 0) { update = true; }
  55299. var size = this.getSize();
  55300. if (clearColor) {
  55301. this._context.fillStyle = clearColor;
  55302. this._context.fillRect(0, 0, size.width, size.height);
  55303. }
  55304. this._context.font = font;
  55305. if (x === null || x === undefined) {
  55306. var textSize = this._context.measureText(text);
  55307. x = (size.width - textSize.width) / 2;
  55308. }
  55309. if (y === null || y === undefined) {
  55310. var fontSize = parseInt((font.replace(/\D/g, '')));
  55311. ;
  55312. y = (size.height / 2) + (fontSize / 3.65);
  55313. }
  55314. this._context.fillStyle = color;
  55315. this._context.fillText(text, x, y);
  55316. if (update) {
  55317. this.update(invertY);
  55318. }
  55319. };
  55320. DynamicTexture.prototype.clone = function () {
  55321. var scene = this.getScene();
  55322. if (!scene) {
  55323. return this;
  55324. }
  55325. var textureSize = this.getSize();
  55326. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  55327. // Base texture
  55328. newTexture.hasAlpha = this.hasAlpha;
  55329. newTexture.level = this.level;
  55330. // Dynamic Texture
  55331. newTexture.wrapU = this.wrapU;
  55332. newTexture.wrapV = this.wrapV;
  55333. return newTexture;
  55334. };
  55335. DynamicTexture.prototype._rebuild = function () {
  55336. this.update();
  55337. };
  55338. return DynamicTexture;
  55339. }(BABYLON.Texture));
  55340. BABYLON.DynamicTexture = DynamicTexture;
  55341. })(BABYLON || (BABYLON = {}));
  55342. //# sourceMappingURL=babylon.dynamicTexture.js.map
  55343. var BABYLON;
  55344. (function (BABYLON) {
  55345. var VideoTexture = /** @class */ (function (_super) {
  55346. __extends(VideoTexture, _super);
  55347. /**
  55348. * Creates a video texture.
  55349. * Sample : https://doc.babylonjs.com/how_to/video_texture
  55350. * @param {string | null} name optional name, will detect from video source, if not defined
  55351. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  55352. * @param {BABYLON.Scene} scene is obviously the current scene.
  55353. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  55354. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  55355. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  55356. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  55357. */
  55358. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  55359. if (generateMipMaps === void 0) { generateMipMaps = false; }
  55360. if (invertY === void 0) { invertY = false; }
  55361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55362. if (settings === void 0) { settings = {
  55363. autoPlay: true,
  55364. loop: true,
  55365. autoUpdateTexture: true,
  55366. }; }
  55367. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55368. _this._createInternalTexture = function () {
  55369. if (_this._texture != null) {
  55370. return;
  55371. }
  55372. if (!_this._engine.needPOTTextures ||
  55373. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  55374. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55375. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55376. }
  55377. else {
  55378. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55379. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55380. _this._generateMipMaps = false;
  55381. }
  55382. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  55383. _this._texture.isReady = true;
  55384. _this._updateInternalTexture();
  55385. };
  55386. _this.reset = function () {
  55387. if (_this._texture == null) {
  55388. return;
  55389. }
  55390. _this._texture.dispose();
  55391. _this._texture = null;
  55392. };
  55393. _this._updateInternalTexture = function (e) {
  55394. if (_this._texture == null || !_this._texture.isReady) {
  55395. return;
  55396. }
  55397. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  55398. return;
  55399. }
  55400. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  55401. };
  55402. _this._engine = _this.getScene().getEngine();
  55403. _this._generateMipMaps = generateMipMaps;
  55404. _this._samplingMode = samplingMode;
  55405. _this.autoUpdateTexture = settings.autoUpdateTexture;
  55406. _this.name = name || _this._getName(src);
  55407. _this.video = _this._getVideo(src);
  55408. if (settings.autoPlay !== undefined) {
  55409. _this.video.autoplay = settings.autoPlay;
  55410. }
  55411. if (settings.loop !== undefined) {
  55412. _this.video.loop = settings.loop;
  55413. }
  55414. _this.video.addEventListener("canplay", _this._createInternalTexture);
  55415. _this.video.addEventListener("paused", _this._updateInternalTexture);
  55416. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  55417. _this.video.addEventListener("emptied", _this.reset);
  55418. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  55419. _this._createInternalTexture();
  55420. }
  55421. return _this;
  55422. }
  55423. VideoTexture.prototype._getName = function (src) {
  55424. if (src instanceof HTMLVideoElement) {
  55425. return src.currentSrc;
  55426. }
  55427. if (typeof src === "object") {
  55428. return src.toString();
  55429. }
  55430. return src;
  55431. };
  55432. ;
  55433. VideoTexture.prototype._getVideo = function (src) {
  55434. if (src instanceof HTMLVideoElement) {
  55435. return src;
  55436. }
  55437. var video = document.createElement("video");
  55438. if (typeof src === "string") {
  55439. video.src = src;
  55440. }
  55441. else {
  55442. src.forEach(function (url) {
  55443. var source = document.createElement("source");
  55444. source.src = url;
  55445. video.appendChild(source);
  55446. });
  55447. }
  55448. return video;
  55449. };
  55450. ;
  55451. /**
  55452. * Internal method to initiate `update`.
  55453. */
  55454. VideoTexture.prototype._rebuild = function () {
  55455. this.update();
  55456. };
  55457. /**
  55458. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  55459. */
  55460. VideoTexture.prototype.update = function () {
  55461. if (!this.autoUpdateTexture) {
  55462. // Expecting user to call `updateTexture` manually
  55463. return;
  55464. }
  55465. this.updateTexture(true);
  55466. };
  55467. /**
  55468. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  55469. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  55470. */
  55471. VideoTexture.prototype.updateTexture = function (isVisible) {
  55472. if (!isVisible) {
  55473. return;
  55474. }
  55475. if (this.video.paused) {
  55476. return;
  55477. }
  55478. this._updateInternalTexture();
  55479. };
  55480. /**
  55481. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  55482. * @param url New url.
  55483. */
  55484. VideoTexture.prototype.updateURL = function (url) {
  55485. this.video.src = url;
  55486. };
  55487. VideoTexture.prototype.dispose = function () {
  55488. _super.prototype.dispose.call(this);
  55489. this.video.removeEventListener("canplay", this._createInternalTexture);
  55490. this.video.removeEventListener("paused", this._updateInternalTexture);
  55491. this.video.removeEventListener("seeked", this._updateInternalTexture);
  55492. this.video.removeEventListener("emptied", this.reset);
  55493. };
  55494. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  55495. var video = document.createElement("video");
  55496. var constraintsDeviceId;
  55497. if (constraints && constraints.deviceId) {
  55498. constraintsDeviceId = {
  55499. exact: constraints.deviceId,
  55500. };
  55501. }
  55502. navigator.getUserMedia =
  55503. navigator.getUserMedia ||
  55504. navigator.webkitGetUserMedia ||
  55505. navigator.mozGetUserMedia ||
  55506. navigator.msGetUserMedia;
  55507. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  55508. if (navigator.getUserMedia) {
  55509. navigator.getUserMedia({
  55510. video: {
  55511. deviceId: constraintsDeviceId,
  55512. width: {
  55513. min: (constraints && constraints.minWidth) || 256,
  55514. max: (constraints && constraints.maxWidth) || 640,
  55515. },
  55516. height: {
  55517. min: (constraints && constraints.minHeight) || 256,
  55518. max: (constraints && constraints.maxHeight) || 480,
  55519. },
  55520. },
  55521. }, function (stream) {
  55522. if (video.mozSrcObject !== undefined) {
  55523. // hack for Firefox < 19
  55524. video.mozSrcObject = stream;
  55525. }
  55526. else {
  55527. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  55528. }
  55529. video.play();
  55530. if (onReady) {
  55531. onReady(new VideoTexture("video", video, scene, true, true));
  55532. }
  55533. }, function (e) {
  55534. BABYLON.Tools.Error(e.name);
  55535. });
  55536. }
  55537. };
  55538. return VideoTexture;
  55539. }(BABYLON.Texture));
  55540. BABYLON.VideoTexture = VideoTexture;
  55541. })(BABYLON || (BABYLON = {}));
  55542. //# sourceMappingURL=babylon.videoTexture.js.map
  55543. var BABYLON;
  55544. (function (BABYLON) {
  55545. var RawTexture = /** @class */ (function (_super) {
  55546. __extends(RawTexture, _super);
  55547. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  55548. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55549. if (invertY === void 0) { invertY = false; }
  55550. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55551. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55552. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55553. _this.format = format;
  55554. _this._engine = scene.getEngine();
  55555. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  55556. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55557. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55558. return _this;
  55559. }
  55560. RawTexture.prototype.update = function (data) {
  55561. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  55562. };
  55563. // Statics
  55564. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55565. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55566. if (invertY === void 0) { invertY = false; }
  55567. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55568. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  55569. };
  55570. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55571. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55572. if (invertY === void 0) { invertY = false; }
  55573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55574. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55575. };
  55576. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55577. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55578. if (invertY === void 0) { invertY = false; }
  55579. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55580. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55581. };
  55582. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55583. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55584. if (invertY === void 0) { invertY = false; }
  55585. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55586. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55587. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  55588. };
  55589. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55590. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55591. if (invertY === void 0) { invertY = false; }
  55592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55593. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55594. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  55595. };
  55596. return RawTexture;
  55597. }(BABYLON.Texture));
  55598. BABYLON.RawTexture = RawTexture;
  55599. })(BABYLON || (BABYLON = {}));
  55600. //# sourceMappingURL=babylon.rawTexture.js.map
  55601. var BABYLON;
  55602. (function (BABYLON) {
  55603. var PostProcess = /** @class */ (function () {
  55604. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  55605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  55606. if (defines === void 0) { defines = null; }
  55607. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55608. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  55609. if (blockCompilation === void 0) { blockCompilation = false; }
  55610. this.name = name;
  55611. this.width = -1;
  55612. this.height = -1;
  55613. this.autoClear = true;
  55614. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  55615. this.animations = new Array();
  55616. /*
  55617. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  55618. Can only be used on a single postprocess or on the last one of a chain.
  55619. */
  55620. this.enablePixelPerfectMode = false;
  55621. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  55622. this.alwaysForcePOT = false;
  55623. this.samples = 1;
  55624. this.adaptScaleToCurrentViewport = false;
  55625. this._reusable = false;
  55626. this._textures = new BABYLON.SmartArray(2);
  55627. this._currentRenderTextureInd = 0;
  55628. this._scaleRatio = new BABYLON.Vector2(1, 1);
  55629. this._texelSize = BABYLON.Vector2.Zero();
  55630. // Events
  55631. /**
  55632. * An event triggered when the postprocess is activated.
  55633. * @type {BABYLON.Observable}
  55634. */
  55635. this.onActivateObservable = new BABYLON.Observable();
  55636. /**
  55637. * An event triggered when the postprocess changes its size.
  55638. * @type {BABYLON.Observable}
  55639. */
  55640. this.onSizeChangedObservable = new BABYLON.Observable();
  55641. /**
  55642. * An event triggered when the postprocess applies its effect.
  55643. * @type {BABYLON.Observable}
  55644. */
  55645. this.onApplyObservable = new BABYLON.Observable();
  55646. /**
  55647. * An event triggered before rendering the postprocess
  55648. * @type {BABYLON.Observable}
  55649. */
  55650. this.onBeforeRenderObservable = new BABYLON.Observable();
  55651. /**
  55652. * An event triggered after rendering the postprocess
  55653. * @type {BABYLON.Observable}
  55654. */
  55655. this.onAfterRenderObservable = new BABYLON.Observable();
  55656. if (camera != null) {
  55657. this._camera = camera;
  55658. this._scene = camera.getScene();
  55659. camera.attachPostProcess(this);
  55660. this._engine = this._scene.getEngine();
  55661. this._scene.postProcesses.push(this);
  55662. }
  55663. else if (engine) {
  55664. this._engine = engine;
  55665. this._engine.postProcesses.push(this);
  55666. }
  55667. this._options = options;
  55668. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  55669. this._reusable = reusable || false;
  55670. this._textureType = textureType;
  55671. this._samplers = samplers || [];
  55672. this._samplers.push("textureSampler");
  55673. this._fragmentUrl = fragmentUrl;
  55674. this._vertexUrl = vertexUrl;
  55675. this._parameters = parameters || [];
  55676. this._parameters.push("scale");
  55677. this._indexParameters = indexParameters;
  55678. if (!blockCompilation) {
  55679. this.updateEffect(defines);
  55680. }
  55681. }
  55682. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55683. set: function (callback) {
  55684. if (this._onActivateObserver) {
  55685. this.onActivateObservable.remove(this._onActivateObserver);
  55686. }
  55687. if (callback) {
  55688. this._onActivateObserver = this.onActivateObservable.add(callback);
  55689. }
  55690. },
  55691. enumerable: true,
  55692. configurable: true
  55693. });
  55694. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55695. set: function (callback) {
  55696. if (this._onSizeChangedObserver) {
  55697. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55698. }
  55699. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55700. },
  55701. enumerable: true,
  55702. configurable: true
  55703. });
  55704. Object.defineProperty(PostProcess.prototype, "onApply", {
  55705. set: function (callback) {
  55706. if (this._onApplyObserver) {
  55707. this.onApplyObservable.remove(this._onApplyObserver);
  55708. }
  55709. this._onApplyObserver = this.onApplyObservable.add(callback);
  55710. },
  55711. enumerable: true,
  55712. configurable: true
  55713. });
  55714. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  55715. set: function (callback) {
  55716. if (this._onBeforeRenderObserver) {
  55717. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55718. }
  55719. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55720. },
  55721. enumerable: true,
  55722. configurable: true
  55723. });
  55724. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  55725. set: function (callback) {
  55726. if (this._onAfterRenderObserver) {
  55727. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55728. }
  55729. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55730. },
  55731. enumerable: true,
  55732. configurable: true
  55733. });
  55734. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  55735. get: function () {
  55736. return this._textures.data[this._currentRenderTextureInd];
  55737. },
  55738. set: function (value) {
  55739. this._forcedOutputTexture = value;
  55740. },
  55741. enumerable: true,
  55742. configurable: true
  55743. });
  55744. PostProcess.prototype.getCamera = function () {
  55745. return this._camera;
  55746. };
  55747. Object.defineProperty(PostProcess.prototype, "texelSize", {
  55748. get: function () {
  55749. if (this._shareOutputWithPostProcess) {
  55750. return this._shareOutputWithPostProcess.texelSize;
  55751. }
  55752. if (this._forcedOutputTexture) {
  55753. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  55754. }
  55755. return this._texelSize;
  55756. },
  55757. enumerable: true,
  55758. configurable: true
  55759. });
  55760. PostProcess.prototype.getEngine = function () {
  55761. return this._engine;
  55762. };
  55763. PostProcess.prototype.getEffect = function () {
  55764. return this._effect;
  55765. };
  55766. PostProcess.prototype.shareOutputWith = function (postProcess) {
  55767. this._disposeTextures();
  55768. this._shareOutputWithPostProcess = postProcess;
  55769. return this;
  55770. };
  55771. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  55772. if (defines === void 0) { defines = null; }
  55773. if (uniforms === void 0) { uniforms = null; }
  55774. if (samplers === void 0) { samplers = null; }
  55775. 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);
  55776. };
  55777. PostProcess.prototype.isReusable = function () {
  55778. return this._reusable;
  55779. };
  55780. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  55781. PostProcess.prototype.markTextureDirty = function () {
  55782. this.width = -1;
  55783. };
  55784. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  55785. var _this = this;
  55786. if (sourceTexture === void 0) { sourceTexture = null; }
  55787. camera = camera || this._camera;
  55788. var scene = camera.getScene();
  55789. var engine = scene.getEngine();
  55790. var maxSize = engine.getCaps().maxTextureSize;
  55791. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  55792. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  55793. var desiredWidth = (this._options.width || requiredWidth);
  55794. var desiredHeight = this._options.height || requiredHeight;
  55795. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  55796. if (this.adaptScaleToCurrentViewport) {
  55797. var currentViewport = engine.currentViewport;
  55798. if (currentViewport) {
  55799. desiredWidth *= currentViewport.width;
  55800. desiredHeight *= currentViewport.height;
  55801. }
  55802. }
  55803. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  55804. if (!this._options.width) {
  55805. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  55806. }
  55807. if (!this._options.height) {
  55808. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  55809. }
  55810. }
  55811. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  55812. if (this._textures.length > 0) {
  55813. for (var i = 0; i < this._textures.length; i++) {
  55814. this._engine._releaseTexture(this._textures.data[i]);
  55815. }
  55816. this._textures.reset();
  55817. }
  55818. this.width = desiredWidth;
  55819. this.height = desiredHeight;
  55820. var textureSize = { width: this.width, height: this.height };
  55821. var textureOptions = {
  55822. generateMipMaps: false,
  55823. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  55824. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  55825. samplingMode: this.renderTargetSamplingMode,
  55826. type: this._textureType
  55827. };
  55828. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55829. if (this._reusable) {
  55830. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55831. }
  55832. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  55833. this.onSizeChangedObservable.notifyObservers(this);
  55834. }
  55835. this._textures.forEach(function (texture) {
  55836. if (texture.samples !== _this.samples) {
  55837. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  55838. }
  55839. });
  55840. }
  55841. var target;
  55842. if (this._shareOutputWithPostProcess) {
  55843. target = this._shareOutputWithPostProcess.outputTexture;
  55844. }
  55845. else if (this._forcedOutputTexture) {
  55846. target = this._forcedOutputTexture;
  55847. this.width = this._forcedOutputTexture.width;
  55848. this.height = this._forcedOutputTexture.height;
  55849. }
  55850. else {
  55851. target = this.outputTexture;
  55852. }
  55853. if (this.enablePixelPerfectMode) {
  55854. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  55855. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  55856. }
  55857. else {
  55858. this._scaleRatio.copyFromFloats(1, 1);
  55859. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  55860. }
  55861. this.onActivateObservable.notifyObservers(camera);
  55862. // Clear
  55863. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  55864. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  55865. }
  55866. if (this._reusable) {
  55867. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  55868. }
  55869. };
  55870. Object.defineProperty(PostProcess.prototype, "isSupported", {
  55871. get: function () {
  55872. return this._effect.isSupported;
  55873. },
  55874. enumerable: true,
  55875. configurable: true
  55876. });
  55877. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  55878. get: function () {
  55879. if (this._shareOutputWithPostProcess) {
  55880. return this._shareOutputWithPostProcess.aspectRatio;
  55881. }
  55882. if (this._forcedOutputTexture) {
  55883. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  55884. }
  55885. return this.width / this.height;
  55886. },
  55887. enumerable: true,
  55888. configurable: true
  55889. });
  55890. /**
  55891. * Get a value indicating if the post-process is ready to be used
  55892. * @returns true if the post-process is ready (shader is compiled)
  55893. */
  55894. PostProcess.prototype.isReady = function () {
  55895. return this._effect && this._effect.isReady();
  55896. };
  55897. PostProcess.prototype.apply = function () {
  55898. // Check
  55899. if (!this._effect || !this._effect.isReady())
  55900. return null;
  55901. // States
  55902. this._engine.enableEffect(this._effect);
  55903. this._engine.setState(false);
  55904. this._engine.setDepthBuffer(false);
  55905. this._engine.setDepthWrite(false);
  55906. // Alpha
  55907. this._engine.setAlphaMode(this.alphaMode);
  55908. if (this.alphaConstants) {
  55909. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  55910. }
  55911. // Texture
  55912. var source;
  55913. if (this._shareOutputWithPostProcess) {
  55914. source = this._shareOutputWithPostProcess.outputTexture;
  55915. }
  55916. else if (this._forcedOutputTexture) {
  55917. source = this._forcedOutputTexture;
  55918. }
  55919. else {
  55920. source = this.outputTexture;
  55921. }
  55922. this._effect._bindTexture("textureSampler", source);
  55923. // Parameters
  55924. this._effect.setVector2("scale", this._scaleRatio);
  55925. this.onApplyObservable.notifyObservers(this._effect);
  55926. return this._effect;
  55927. };
  55928. PostProcess.prototype._disposeTextures = function () {
  55929. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  55930. return;
  55931. }
  55932. if (this._textures.length > 0) {
  55933. for (var i = 0; i < this._textures.length; i++) {
  55934. this._engine._releaseTexture(this._textures.data[i]);
  55935. }
  55936. }
  55937. this._textures.dispose();
  55938. };
  55939. PostProcess.prototype.dispose = function (camera) {
  55940. camera = camera || this._camera;
  55941. this._disposeTextures();
  55942. if (this._scene) {
  55943. var index_1 = this._scene.postProcesses.indexOf(this);
  55944. if (index_1 !== -1) {
  55945. this._scene.postProcesses.splice(index_1, 1);
  55946. }
  55947. }
  55948. else {
  55949. var index_2 = this._engine.postProcesses.indexOf(this);
  55950. if (index_2 !== -1) {
  55951. this._engine.postProcesses.splice(index_2, 1);
  55952. }
  55953. }
  55954. if (!camera) {
  55955. return;
  55956. }
  55957. camera.detachPostProcess(this);
  55958. var index = camera._postProcesses.indexOf(this);
  55959. if (index === 0 && camera._postProcesses.length > 0) {
  55960. this._camera._postProcesses[0].markTextureDirty();
  55961. }
  55962. this.onActivateObservable.clear();
  55963. this.onAfterRenderObservable.clear();
  55964. this.onApplyObservable.clear();
  55965. this.onBeforeRenderObservable.clear();
  55966. this.onSizeChangedObservable.clear();
  55967. };
  55968. return PostProcess;
  55969. }());
  55970. BABYLON.PostProcess = PostProcess;
  55971. })(BABYLON || (BABYLON = {}));
  55972. //# sourceMappingURL=babylon.postProcess.js.map
  55973. var BABYLON;
  55974. (function (BABYLON) {
  55975. var PassPostProcess = /** @class */ (function (_super) {
  55976. __extends(PassPostProcess, _super);
  55977. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55978. if (camera === void 0) { camera = null; }
  55979. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55980. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  55981. }
  55982. return PassPostProcess;
  55983. }(BABYLON.PostProcess));
  55984. BABYLON.PassPostProcess = PassPostProcess;
  55985. })(BABYLON || (BABYLON = {}));
  55986. //# sourceMappingURL=babylon.passPostProcess.js.map
  55987. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55988. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55989. s = arguments[i];
  55990. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55991. t[p] = s[p];
  55992. }
  55993. return t;
  55994. };
  55995. var BABYLON;
  55996. (function (BABYLON) {
  55997. /**
  55998. * Default implementation of @see IShadowGenerator.
  55999. * This is the main object responsible of generating shadows in the framework.
  56000. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  56001. */
  56002. var ShadowGenerator = /** @class */ (function () {
  56003. /**
  56004. * Creates a ShadowGenerator object.
  56005. * A ShadowGenerator is the required tool to use the shadows.
  56006. * Each light casting shadows needs to use its own ShadowGenerator.
  56007. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  56008. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  56009. * @param light The light object generating the shadows.
  56010. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  56011. */
  56012. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  56013. this._bias = 0.00005;
  56014. this._blurBoxOffset = 1;
  56015. this._blurScale = 2;
  56016. this._blurKernel = 1;
  56017. this._useKernelBlur = false;
  56018. this._filter = ShadowGenerator.FILTER_NONE;
  56019. this._darkness = 0;
  56020. this._transparencyShadow = false;
  56021. /**
  56022. * Controls the extent to which the shadows fade out at the edge of the frustum
  56023. * Used only by directionals and spots
  56024. */
  56025. this.frustumEdgeFalloff = 0;
  56026. /**
  56027. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  56028. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  56029. * It might on the other hand introduce peter panning.
  56030. */
  56031. this.forceBackFacesOnly = false;
  56032. this._lightDirection = BABYLON.Vector3.Zero();
  56033. this._viewMatrix = BABYLON.Matrix.Zero();
  56034. this._projectionMatrix = BABYLON.Matrix.Zero();
  56035. this._transformMatrix = BABYLON.Matrix.Zero();
  56036. this._currentFaceIndex = 0;
  56037. this._currentFaceIndexCache = 0;
  56038. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  56039. this._mapSize = mapSize;
  56040. this._light = light;
  56041. this._scene = light.getScene();
  56042. light._shadowGenerator = this;
  56043. // Texture type fallback from float to int if not supported.
  56044. var caps = this._scene.getEngine().getCaps();
  56045. if (!useFullFloatFirst) {
  56046. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56047. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56048. }
  56049. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56050. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56051. }
  56052. else {
  56053. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56054. }
  56055. }
  56056. else {
  56057. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  56058. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56059. }
  56060. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  56061. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56062. }
  56063. else {
  56064. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56065. }
  56066. }
  56067. this._initializeGenerator();
  56068. }
  56069. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  56070. /**
  56071. * Shadow generator mode None: no filtering applied.
  56072. */
  56073. get: function () {
  56074. return ShadowGenerator._FILTER_NONE;
  56075. },
  56076. enumerable: true,
  56077. configurable: true
  56078. });
  56079. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  56080. /**
  56081. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  56082. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  56083. */
  56084. get: function () {
  56085. return ShadowGenerator._FILTER_POISSONSAMPLING;
  56086. },
  56087. enumerable: true,
  56088. configurable: true
  56089. });
  56090. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  56091. /**
  56092. * Shadow generator mode ESM: Exponential Shadow Mapping.
  56093. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56094. */
  56095. get: function () {
  56096. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  56097. },
  56098. enumerable: true,
  56099. configurable: true
  56100. });
  56101. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  56102. /**
  56103. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  56104. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56105. */
  56106. get: function () {
  56107. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  56108. },
  56109. enumerable: true,
  56110. configurable: true
  56111. });
  56112. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  56113. /**
  56114. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  56115. * edge artifacts on steep falloff.
  56116. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56117. */
  56118. get: function () {
  56119. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56120. },
  56121. enumerable: true,
  56122. configurable: true
  56123. });
  56124. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  56125. /**
  56126. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  56127. * edge artifacts on steep falloff.
  56128. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  56129. */
  56130. get: function () {
  56131. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56132. },
  56133. enumerable: true,
  56134. configurable: true
  56135. });
  56136. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  56137. /**
  56138. * Gets the bias: offset applied on the depth preventing acnea.
  56139. */
  56140. get: function () {
  56141. return this._bias;
  56142. },
  56143. /**
  56144. * Sets the bias: offset applied on the depth preventing acnea.
  56145. */
  56146. set: function (bias) {
  56147. this._bias = bias;
  56148. },
  56149. enumerable: true,
  56150. configurable: true
  56151. });
  56152. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  56153. /**
  56154. * Gets the blur box offset: offset applied during the blur pass.
  56155. * Only usefull if useKernelBlur = false
  56156. */
  56157. get: function () {
  56158. return this._blurBoxOffset;
  56159. },
  56160. /**
  56161. * Sets the blur box offset: offset applied during the blur pass.
  56162. * Only usefull if useKernelBlur = false
  56163. */
  56164. set: function (value) {
  56165. if (this._blurBoxOffset === value) {
  56166. return;
  56167. }
  56168. this._blurBoxOffset = value;
  56169. this._disposeBlurPostProcesses();
  56170. },
  56171. enumerable: true,
  56172. configurable: true
  56173. });
  56174. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  56175. /**
  56176. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  56177. * 2 means half of the size.
  56178. */
  56179. get: function () {
  56180. return this._blurScale;
  56181. },
  56182. /**
  56183. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  56184. * 2 means half of the size.
  56185. */
  56186. set: function (value) {
  56187. if (this._blurScale === value) {
  56188. return;
  56189. }
  56190. this._blurScale = value;
  56191. this._disposeBlurPostProcesses();
  56192. },
  56193. enumerable: true,
  56194. configurable: true
  56195. });
  56196. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  56197. /**
  56198. * Gets the blur kernel: kernel size of the blur pass.
  56199. * Only usefull if useKernelBlur = true
  56200. */
  56201. get: function () {
  56202. return this._blurKernel;
  56203. },
  56204. /**
  56205. * Sets the blur kernel: kernel size of the blur pass.
  56206. * Only usefull if useKernelBlur = true
  56207. */
  56208. set: function (value) {
  56209. if (this._blurKernel === value) {
  56210. return;
  56211. }
  56212. this._blurKernel = value;
  56213. this._disposeBlurPostProcesses();
  56214. },
  56215. enumerable: true,
  56216. configurable: true
  56217. });
  56218. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  56219. /**
  56220. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  56221. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56222. */
  56223. get: function () {
  56224. return this._useKernelBlur;
  56225. },
  56226. /**
  56227. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  56228. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  56229. */
  56230. set: function (value) {
  56231. if (this._useKernelBlur === value) {
  56232. return;
  56233. }
  56234. this._useKernelBlur = value;
  56235. this._disposeBlurPostProcesses();
  56236. },
  56237. enumerable: true,
  56238. configurable: true
  56239. });
  56240. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  56241. /**
  56242. * Gets the depth scale used in ESM mode.
  56243. */
  56244. get: function () {
  56245. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  56246. },
  56247. /**
  56248. * Sets the depth scale used in ESM mode.
  56249. * This can override the scale stored on the light.
  56250. */
  56251. set: function (value) {
  56252. this._depthScale = value;
  56253. },
  56254. enumerable: true,
  56255. configurable: true
  56256. });
  56257. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  56258. /**
  56259. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  56260. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56261. */
  56262. get: function () {
  56263. return this._filter;
  56264. },
  56265. /**
  56266. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  56267. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  56268. */
  56269. set: function (value) {
  56270. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  56271. if (this._light.needCube()) {
  56272. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56273. this.useExponentialShadowMap = true;
  56274. return;
  56275. }
  56276. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56277. this.useCloseExponentialShadowMap = true;
  56278. return;
  56279. }
  56280. }
  56281. if (this._filter === value) {
  56282. return;
  56283. }
  56284. this._filter = value;
  56285. this._disposeBlurPostProcesses();
  56286. this._applyFilterValues();
  56287. this._light._markMeshesAsLightDirty();
  56288. },
  56289. enumerable: true,
  56290. configurable: true
  56291. });
  56292. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  56293. /**
  56294. * Gets if the current filter is set to Poisson Sampling aka PCF.
  56295. */
  56296. get: function () {
  56297. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  56298. },
  56299. /**
  56300. * Sets the current filter to Poisson Sampling aka PCF.
  56301. */
  56302. set: function (value) {
  56303. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  56304. return;
  56305. }
  56306. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  56307. },
  56308. enumerable: true,
  56309. configurable: true
  56310. });
  56311. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  56312. /**
  56313. * Gets if the current filter is set to VSM.
  56314. * DEPRECATED. Should use useExponentialShadowMap instead.
  56315. */
  56316. get: function () {
  56317. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56318. return this.useExponentialShadowMap;
  56319. },
  56320. /**
  56321. * Sets the current filter is to VSM.
  56322. * DEPRECATED. Should use useExponentialShadowMap instead.
  56323. */
  56324. set: function (value) {
  56325. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  56326. this.useExponentialShadowMap = value;
  56327. },
  56328. enumerable: true,
  56329. configurable: true
  56330. });
  56331. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  56332. /**
  56333. * Gets if the current filter is set to blurred VSM.
  56334. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56335. */
  56336. get: function () {
  56337. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56338. return this.useBlurExponentialShadowMap;
  56339. },
  56340. /**
  56341. * Sets the current filter is to blurred VSM.
  56342. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  56343. */
  56344. set: function (value) {
  56345. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  56346. this.useBlurExponentialShadowMap = value;
  56347. },
  56348. enumerable: true,
  56349. configurable: true
  56350. });
  56351. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  56352. /**
  56353. * Gets if the current filter is set to ESM.
  56354. */
  56355. get: function () {
  56356. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  56357. },
  56358. /**
  56359. * Sets the current filter is to ESM.
  56360. */
  56361. set: function (value) {
  56362. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  56363. return;
  56364. }
  56365. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56366. },
  56367. enumerable: true,
  56368. configurable: true
  56369. });
  56370. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  56371. /**
  56372. * Gets if the current filter is set to filtered ESM.
  56373. */
  56374. get: function () {
  56375. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  56376. },
  56377. /**
  56378. * Gets if the current filter is set to filtered ESM.
  56379. */
  56380. set: function (value) {
  56381. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  56382. return;
  56383. }
  56384. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56385. },
  56386. enumerable: true,
  56387. configurable: true
  56388. });
  56389. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  56390. /**
  56391. * Gets if the current filter is set to "close ESM" (using the inverse of the
  56392. * exponential to prevent steep falloff artifacts).
  56393. */
  56394. get: function () {
  56395. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  56396. },
  56397. /**
  56398. * Sets the current filter to "close ESM" (using the inverse of the
  56399. * exponential to prevent steep falloff artifacts).
  56400. */
  56401. set: function (value) {
  56402. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  56403. return;
  56404. }
  56405. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56406. },
  56407. enumerable: true,
  56408. configurable: true
  56409. });
  56410. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  56411. /**
  56412. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  56413. * exponential to prevent steep falloff artifacts).
  56414. */
  56415. get: function () {
  56416. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  56417. },
  56418. /**
  56419. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  56420. * exponential to prevent steep falloff artifacts).
  56421. */
  56422. set: function (value) {
  56423. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  56424. return;
  56425. }
  56426. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  56427. },
  56428. enumerable: true,
  56429. configurable: true
  56430. });
  56431. /**
  56432. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  56433. * 0 means strongest and 1 would means no shadow.
  56434. * @returns the darkness.
  56435. */
  56436. ShadowGenerator.prototype.getDarkness = function () {
  56437. return this._darkness;
  56438. };
  56439. /**
  56440. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  56441. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  56442. * @returns the shadow generator allowing fluent coding.
  56443. */
  56444. ShadowGenerator.prototype.setDarkness = function (darkness) {
  56445. if (darkness >= 1.0)
  56446. this._darkness = 1.0;
  56447. else if (darkness <= 0.0)
  56448. this._darkness = 0.0;
  56449. else
  56450. this._darkness = darkness;
  56451. return this;
  56452. };
  56453. /**
  56454. * Sets the ability to have transparent shadow (boolean).
  56455. * @param transparent True if transparent else False
  56456. * @returns the shadow generator allowing fluent coding
  56457. */
  56458. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  56459. this._transparencyShadow = transparent;
  56460. return this;
  56461. };
  56462. /**
  56463. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  56464. * @returns The render target texture if present otherwise, null
  56465. */
  56466. ShadowGenerator.prototype.getShadowMap = function () {
  56467. return this._shadowMap;
  56468. };
  56469. /**
  56470. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  56471. * @returns The render target texture if the shadow map is present otherwise, null
  56472. */
  56473. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  56474. if (this._shadowMap2) {
  56475. return this._shadowMap2;
  56476. }
  56477. return this._shadowMap;
  56478. };
  56479. /**
  56480. * Helper function to add a mesh and its descendants to the list of shadow casters.
  56481. * @param mesh Mesh to add
  56482. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  56483. * @returns the Shadow Generator itself
  56484. */
  56485. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  56486. if (includeDescendants === void 0) { includeDescendants = true; }
  56487. if (!this._shadowMap) {
  56488. return this;
  56489. }
  56490. if (!this._shadowMap.renderList) {
  56491. this._shadowMap.renderList = [];
  56492. }
  56493. this._shadowMap.renderList.push(mesh);
  56494. if (includeDescendants) {
  56495. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  56496. }
  56497. return this;
  56498. var _a;
  56499. };
  56500. /**
  56501. * Helper function to remove a mesh and its descendants from the list of shadow casters
  56502. * @param mesh Mesh to remove
  56503. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  56504. * @returns the Shadow Generator itself
  56505. */
  56506. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  56507. if (includeDescendants === void 0) { includeDescendants = true; }
  56508. if (!this._shadowMap || !this._shadowMap.renderList) {
  56509. return this;
  56510. }
  56511. var index = this._shadowMap.renderList.indexOf(mesh);
  56512. if (index !== -1) {
  56513. this._shadowMap.renderList.splice(index, 1);
  56514. }
  56515. if (includeDescendants) {
  56516. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  56517. var child = _a[_i];
  56518. this.removeShadowCaster(child);
  56519. }
  56520. }
  56521. return this;
  56522. };
  56523. /**
  56524. * Returns the associated light object.
  56525. * @returns the light generating the shadow
  56526. */
  56527. ShadowGenerator.prototype.getLight = function () {
  56528. return this._light;
  56529. };
  56530. ShadowGenerator.prototype._initializeGenerator = function () {
  56531. this._light._markMeshesAsLightDirty();
  56532. this._initializeShadowMap();
  56533. };
  56534. ShadowGenerator.prototype._initializeShadowMap = function () {
  56535. var _this = this;
  56536. // Render target
  56537. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  56538. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56539. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56540. this._shadowMap.anisotropicFilteringLevel = 1;
  56541. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56542. this._shadowMap.renderParticles = false;
  56543. this._shadowMap.ignoreCameraViewport = true;
  56544. // Record Face Index before render.
  56545. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  56546. _this._currentFaceIndex = faceIndex;
  56547. });
  56548. // Custom render function.
  56549. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  56550. // Blur if required afer render.
  56551. this._shadowMap.onAfterUnbindObservable.add(function () {
  56552. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  56553. return;
  56554. }
  56555. var shadowMap = _this.getShadowMapForRendering();
  56556. if (shadowMap) {
  56557. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  56558. }
  56559. });
  56560. // Clear according to the chosen filter.
  56561. this._shadowMap.onClearObservable.add(function (engine) {
  56562. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  56563. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  56564. }
  56565. else {
  56566. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56567. }
  56568. });
  56569. };
  56570. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  56571. var _this = this;
  56572. var engine = this._scene.getEngine();
  56573. var targetSize = this._mapSize / this.blurScale;
  56574. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  56575. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  56576. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56577. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56578. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56579. }
  56580. if (this.useKernelBlur) {
  56581. 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);
  56582. this._kernelBlurXPostprocess.width = targetSize;
  56583. this._kernelBlurXPostprocess.height = targetSize;
  56584. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  56585. effect.setTexture("textureSampler", _this._shadowMap);
  56586. });
  56587. 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);
  56588. this._kernelBlurXPostprocess.autoClear = false;
  56589. this._kernelBlurYPostprocess.autoClear = false;
  56590. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56591. this._kernelBlurXPostprocess.packedFloat = true;
  56592. this._kernelBlurYPostprocess.packedFloat = true;
  56593. }
  56594. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  56595. }
  56596. else {
  56597. 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);
  56598. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  56599. effect.setFloat2("screenSize", targetSize, targetSize);
  56600. effect.setTexture("textureSampler", _this._shadowMap);
  56601. });
  56602. this._boxBlurPostprocess.autoClear = false;
  56603. this._blurPostProcesses = [this._boxBlurPostprocess];
  56604. }
  56605. };
  56606. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56607. var index;
  56608. var engine = this._scene.getEngine();
  56609. if (depthOnlySubMeshes.length) {
  56610. engine.setColorWrite(false);
  56611. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56612. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  56613. }
  56614. engine.setColorWrite(true);
  56615. }
  56616. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56617. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  56618. }
  56619. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56620. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  56621. }
  56622. if (this._transparencyShadow) {
  56623. for (index = 0; index < transparentSubMeshes.length; index++) {
  56624. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  56625. }
  56626. }
  56627. };
  56628. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  56629. var _this = this;
  56630. var mesh = subMesh.getRenderingMesh();
  56631. var scene = this._scene;
  56632. var engine = scene.getEngine();
  56633. var material = subMesh.getMaterial();
  56634. if (!material) {
  56635. return;
  56636. }
  56637. // Culling
  56638. engine.setState(material.backFaceCulling);
  56639. // Managing instances
  56640. var batch = mesh._getInstancesRenderList(subMesh._id);
  56641. if (batch.mustReturn) {
  56642. return;
  56643. }
  56644. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  56645. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  56646. engine.enableEffect(this._effect);
  56647. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  56648. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  56649. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  56650. this._effect.setVector3("lightPosition", this.getLight().position);
  56651. if (scene.activeCamera) {
  56652. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  56653. }
  56654. // Alpha test
  56655. if (material && material.needAlphaTesting()) {
  56656. var alphaTexture = material.getAlphaTestTexture();
  56657. if (alphaTexture) {
  56658. this._effect.setTexture("diffuseSampler", alphaTexture);
  56659. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  56660. }
  56661. }
  56662. // Bones
  56663. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56664. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  56665. }
  56666. if (this.forceBackFacesOnly) {
  56667. engine.setState(true, 0, false, true);
  56668. }
  56669. // Draw
  56670. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56671. if (this.forceBackFacesOnly) {
  56672. engine.setState(true, 0, false, false);
  56673. }
  56674. }
  56675. else {
  56676. // Need to reset refresh rate of the shadowMap
  56677. if (this._shadowMap) {
  56678. this._shadowMap.resetRefreshCounter();
  56679. }
  56680. }
  56681. };
  56682. ShadowGenerator.prototype._applyFilterValues = function () {
  56683. if (!this._shadowMap) {
  56684. return;
  56685. }
  56686. if (this.filter === ShadowGenerator.FILTER_NONE) {
  56687. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56688. }
  56689. else {
  56690. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56691. }
  56692. };
  56693. /**
  56694. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  56695. * @param onCompiled Callback triggered at the and of the effects compilation
  56696. * @param options Sets of optional options forcing the compilation with different modes
  56697. */
  56698. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  56699. var _this = this;
  56700. var localOptions = __assign({ useInstances: false }, options);
  56701. var shadowMap = this.getShadowMap();
  56702. if (!shadowMap) {
  56703. if (onCompiled) {
  56704. onCompiled(this);
  56705. }
  56706. return;
  56707. }
  56708. var renderList = shadowMap.renderList;
  56709. if (!renderList) {
  56710. if (onCompiled) {
  56711. onCompiled(this);
  56712. }
  56713. return;
  56714. }
  56715. var subMeshes = new Array();
  56716. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  56717. var mesh = renderList_1[_i];
  56718. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  56719. }
  56720. if (subMeshes.length === 0) {
  56721. if (onCompiled) {
  56722. onCompiled(this);
  56723. }
  56724. return;
  56725. }
  56726. var currentIndex = 0;
  56727. var checkReady = function () {
  56728. if (!_this._scene || !_this._scene.getEngine()) {
  56729. return;
  56730. }
  56731. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  56732. currentIndex++;
  56733. if (currentIndex >= subMeshes.length) {
  56734. if (onCompiled) {
  56735. onCompiled(_this);
  56736. }
  56737. return;
  56738. }
  56739. }
  56740. setTimeout(checkReady, 16);
  56741. };
  56742. checkReady();
  56743. };
  56744. /**
  56745. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  56746. * @param subMesh The submesh we want to render in the shadow map
  56747. * @param useInstances Defines wether will draw in the map using instances
  56748. * @returns true if ready otherwise, false
  56749. */
  56750. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  56751. var defines = [];
  56752. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56753. defines.push("#define FLOAT");
  56754. }
  56755. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56756. defines.push("#define ESM");
  56757. }
  56758. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56759. var mesh = subMesh.getMesh();
  56760. var material = subMesh.getMaterial();
  56761. // Alpha test
  56762. if (material && material.needAlphaTesting()) {
  56763. var alphaTexture = material.getAlphaTestTexture();
  56764. if (alphaTexture) {
  56765. defines.push("#define ALPHATEST");
  56766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56767. attribs.push(BABYLON.VertexBuffer.UVKind);
  56768. defines.push("#define UV1");
  56769. }
  56770. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56771. if (alphaTexture.coordinatesIndex === 1) {
  56772. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56773. defines.push("#define UV2");
  56774. }
  56775. }
  56776. }
  56777. }
  56778. // Bones
  56779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56782. if (mesh.numBoneInfluencers > 4) {
  56783. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56784. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56785. }
  56786. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56787. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56788. }
  56789. else {
  56790. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56791. }
  56792. // Instances
  56793. if (useInstances) {
  56794. defines.push("#define INSTANCES");
  56795. attribs.push("world0");
  56796. attribs.push("world1");
  56797. attribs.push("world2");
  56798. attribs.push("world3");
  56799. }
  56800. // Get correct effect
  56801. var join = defines.join("\n");
  56802. if (this._cachedDefines !== join) {
  56803. this._cachedDefines = join;
  56804. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  56805. }
  56806. if (!this._effect.isReady()) {
  56807. return false;
  56808. }
  56809. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56810. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  56811. this._initializeBlurRTTAndPostProcesses();
  56812. }
  56813. }
  56814. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  56815. return false;
  56816. }
  56817. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  56818. return false;
  56819. }
  56820. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  56821. return false;
  56822. }
  56823. return true;
  56824. };
  56825. /**
  56826. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  56827. * @param defines Defines of the material we want to update
  56828. * @param lightIndex Index of the light in the enabled light list of the material
  56829. */
  56830. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  56831. var scene = this._scene;
  56832. var light = this._light;
  56833. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56834. return;
  56835. }
  56836. defines["SHADOW" + lightIndex] = true;
  56837. if (this.usePoissonSampling) {
  56838. defines["SHADOWPCF" + lightIndex] = true;
  56839. }
  56840. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56841. defines["SHADOWESM" + lightIndex] = true;
  56842. }
  56843. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56844. defines["SHADOWCLOSEESM" + lightIndex] = true;
  56845. }
  56846. if (light.needCube()) {
  56847. defines["SHADOWCUBE" + lightIndex] = true;
  56848. }
  56849. };
  56850. /**
  56851. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  56852. * defined in the generator but impacting the effect).
  56853. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  56854. * @param effect The effect we are binfing the information for
  56855. */
  56856. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  56857. var light = this._light;
  56858. var scene = this._scene;
  56859. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56860. return;
  56861. }
  56862. var camera = scene.activeCamera;
  56863. if (!camera) {
  56864. return;
  56865. }
  56866. var shadowMap = this.getShadowMap();
  56867. if (!shadowMap) {
  56868. return;
  56869. }
  56870. if (!light.needCube()) {
  56871. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  56872. }
  56873. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  56874. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  56875. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  56876. };
  56877. /**
  56878. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  56879. * (eq to shadow prjection matrix * light transform matrix)
  56880. * @returns The transform matrix used to create the shadow map
  56881. */
  56882. ShadowGenerator.prototype.getTransformMatrix = function () {
  56883. var scene = this._scene;
  56884. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  56885. return this._transformMatrix;
  56886. }
  56887. this._currentRenderID = scene.getRenderId();
  56888. this._currentFaceIndexCache = this._currentFaceIndex;
  56889. var lightPosition = this._light.position;
  56890. if (this._light.computeTransformedInformation()) {
  56891. lightPosition = this._light.transformedPosition;
  56892. }
  56893. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  56894. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  56895. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  56896. }
  56897. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  56898. this._cachedPosition = lightPosition.clone();
  56899. this._cachedDirection = this._lightDirection.clone();
  56900. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  56901. var shadowMap = this.getShadowMap();
  56902. if (shadowMap) {
  56903. var renderList = shadowMap.renderList;
  56904. if (renderList) {
  56905. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  56906. }
  56907. }
  56908. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  56909. }
  56910. return this._transformMatrix;
  56911. };
  56912. /**
  56913. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  56914. * Cube and 2D textures for instance.
  56915. */
  56916. ShadowGenerator.prototype.recreateShadowMap = function () {
  56917. var shadowMap = this._shadowMap;
  56918. if (!shadowMap) {
  56919. return;
  56920. }
  56921. // Track render list.
  56922. var renderList = shadowMap.renderList;
  56923. // Clean up existing data.
  56924. this._disposeRTTandPostProcesses();
  56925. // Reinitializes.
  56926. this._initializeGenerator();
  56927. // Reaffect the filter to ensure a correct fallback if necessary.
  56928. this.filter = this.filter;
  56929. // Reaffect the filter.
  56930. this._applyFilterValues();
  56931. // Reaffect Render List.
  56932. this._shadowMap.renderList = renderList;
  56933. };
  56934. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  56935. if (this._shadowMap2) {
  56936. this._shadowMap2.dispose();
  56937. this._shadowMap2 = null;
  56938. }
  56939. if (this._boxBlurPostprocess) {
  56940. this._boxBlurPostprocess.dispose();
  56941. this._boxBlurPostprocess = null;
  56942. }
  56943. if (this._kernelBlurXPostprocess) {
  56944. this._kernelBlurXPostprocess.dispose();
  56945. this._kernelBlurXPostprocess = null;
  56946. }
  56947. if (this._kernelBlurYPostprocess) {
  56948. this._kernelBlurYPostprocess.dispose();
  56949. this._kernelBlurYPostprocess = null;
  56950. }
  56951. this._blurPostProcesses = [];
  56952. };
  56953. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  56954. if (this._shadowMap) {
  56955. this._shadowMap.dispose();
  56956. this._shadowMap = null;
  56957. }
  56958. this._disposeBlurPostProcesses();
  56959. };
  56960. /**
  56961. * Disposes the ShadowGenerator.
  56962. * Returns nothing.
  56963. */
  56964. ShadowGenerator.prototype.dispose = function () {
  56965. this._disposeRTTandPostProcesses();
  56966. if (this._light) {
  56967. this._light._shadowGenerator = null;
  56968. this._light._markMeshesAsLightDirty();
  56969. }
  56970. };
  56971. /**
  56972. * Serializes the shadow generator setup to a json object.
  56973. * @returns The serialized JSON object
  56974. */
  56975. ShadowGenerator.prototype.serialize = function () {
  56976. var serializationObject = {};
  56977. var shadowMap = this.getShadowMap();
  56978. if (!shadowMap) {
  56979. return serializationObject;
  56980. }
  56981. serializationObject.lightId = this._light.id;
  56982. serializationObject.mapSize = shadowMap.getRenderSize();
  56983. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  56984. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  56985. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56986. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56987. serializationObject.usePoissonSampling = this.usePoissonSampling;
  56988. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  56989. serializationObject.depthScale = this.depthScale;
  56990. serializationObject.darkness = this.getDarkness();
  56991. serializationObject.blurBoxOffset = this.blurBoxOffset;
  56992. serializationObject.blurKernel = this.blurKernel;
  56993. serializationObject.blurScale = this.blurScale;
  56994. serializationObject.useKernelBlur = this.useKernelBlur;
  56995. serializationObject.transparencyShadow = this._transparencyShadow;
  56996. serializationObject.renderList = [];
  56997. if (shadowMap.renderList) {
  56998. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  56999. var mesh = shadowMap.renderList[meshIndex];
  57000. serializationObject.renderList.push(mesh.id);
  57001. }
  57002. }
  57003. return serializationObject;
  57004. };
  57005. /**
  57006. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  57007. * @param parsedShadowGenerator The JSON object to parse
  57008. * @param scene The scene to create the shadow map for
  57009. * @returns The parsed shadow generator
  57010. */
  57011. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  57012. //casting to point light, as light is missing the position attr and typescript complains.
  57013. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  57014. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  57015. var shadowMap = shadowGenerator.getShadowMap();
  57016. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  57017. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  57018. meshes.forEach(function (mesh) {
  57019. if (!shadowMap) {
  57020. return;
  57021. }
  57022. if (!shadowMap.renderList) {
  57023. shadowMap.renderList = [];
  57024. }
  57025. shadowMap.renderList.push(mesh);
  57026. });
  57027. }
  57028. if (parsedShadowGenerator.usePoissonSampling) {
  57029. shadowGenerator.usePoissonSampling = true;
  57030. }
  57031. else if (parsedShadowGenerator.useExponentialShadowMap) {
  57032. shadowGenerator.useExponentialShadowMap = true;
  57033. }
  57034. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  57035. shadowGenerator.useBlurExponentialShadowMap = true;
  57036. }
  57037. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  57038. shadowGenerator.useCloseExponentialShadowMap = true;
  57039. }
  57040. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  57041. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  57042. }
  57043. else if (parsedShadowGenerator.useVarianceShadowMap) {
  57044. shadowGenerator.useExponentialShadowMap = true;
  57045. }
  57046. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  57047. shadowGenerator.useBlurExponentialShadowMap = true;
  57048. }
  57049. if (parsedShadowGenerator.depthScale) {
  57050. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  57051. }
  57052. if (parsedShadowGenerator.blurScale) {
  57053. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  57054. }
  57055. if (parsedShadowGenerator.blurBoxOffset) {
  57056. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  57057. }
  57058. if (parsedShadowGenerator.useKernelBlur) {
  57059. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  57060. }
  57061. if (parsedShadowGenerator.blurKernel) {
  57062. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  57063. }
  57064. if (parsedShadowGenerator.bias !== undefined) {
  57065. shadowGenerator.bias = parsedShadowGenerator.bias;
  57066. }
  57067. if (parsedShadowGenerator.darkness) {
  57068. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  57069. }
  57070. if (parsedShadowGenerator.transparencyShadow) {
  57071. shadowGenerator.setTransparencyShadow(true);
  57072. }
  57073. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  57074. return shadowGenerator;
  57075. };
  57076. ShadowGenerator._FILTER_NONE = 0;
  57077. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  57078. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  57079. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  57080. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  57081. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  57082. return ShadowGenerator;
  57083. }());
  57084. BABYLON.ShadowGenerator = ShadowGenerator;
  57085. })(BABYLON || (BABYLON = {}));
  57086. //# sourceMappingURL=babylon.shadowGenerator.js.map
  57087. var BABYLON;
  57088. (function (BABYLON) {
  57089. var DefaultLoadingScreen = /** @class */ (function () {
  57090. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  57091. if (_loadingText === void 0) { _loadingText = ""; }
  57092. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  57093. var _this = this;
  57094. this._renderingCanvas = _renderingCanvas;
  57095. this._loadingText = _loadingText;
  57096. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  57097. // Resize
  57098. this._resizeLoadingUI = function () {
  57099. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  57100. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  57101. if (!_this._loadingDiv) {
  57102. return;
  57103. }
  57104. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  57105. _this._loadingDiv.style.left = canvasRect.left + "px";
  57106. _this._loadingDiv.style.top = canvasRect.top + "px";
  57107. _this._loadingDiv.style.width = canvasRect.width + "px";
  57108. _this._loadingDiv.style.height = canvasRect.height + "px";
  57109. };
  57110. }
  57111. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  57112. if (this._loadingDiv) {
  57113. // Do not add a loading screen if there is already one
  57114. return;
  57115. }
  57116. this._loadingDiv = document.createElement("div");
  57117. this._loadingDiv.id = "babylonjsLoadingDiv";
  57118. this._loadingDiv.style.opacity = "0";
  57119. this._loadingDiv.style.transition = "opacity 1.5s ease";
  57120. this._loadingDiv.style.pointerEvents = "none";
  57121. // Loading text
  57122. this._loadingTextDiv = document.createElement("div");
  57123. this._loadingTextDiv.style.position = "absolute";
  57124. this._loadingTextDiv.style.left = "0";
  57125. this._loadingTextDiv.style.top = "50%";
  57126. this._loadingTextDiv.style.marginTop = "80px";
  57127. this._loadingTextDiv.style.width = "100%";
  57128. this._loadingTextDiv.style.height = "20px";
  57129. this._loadingTextDiv.style.fontFamily = "Arial";
  57130. this._loadingTextDiv.style.fontSize = "14px";
  57131. this._loadingTextDiv.style.color = "white";
  57132. this._loadingTextDiv.style.textAlign = "center";
  57133. this._loadingTextDiv.innerHTML = "Loading";
  57134. this._loadingDiv.appendChild(this._loadingTextDiv);
  57135. //set the predefined text
  57136. this._loadingTextDiv.innerHTML = this._loadingText;
  57137. // Generating keyframes
  57138. var style = document.createElement('style');
  57139. style.type = 'text/css';
  57140. 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 }";
  57141. style.innerHTML = keyFrames;
  57142. document.getElementsByTagName('head')[0].appendChild(style);
  57143. // Loading img
  57144. var imgBack = new Image();
  57145. 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";
  57146. imgBack.style.position = "absolute";
  57147. imgBack.style.left = "50%";
  57148. imgBack.style.top = "50%";
  57149. imgBack.style.marginLeft = "-60px";
  57150. imgBack.style.marginTop = "-60px";
  57151. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  57152. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  57153. imgBack.style.transformOrigin = "50% 50%";
  57154. imgBack.style.webkitTransformOrigin = "50% 50%";
  57155. this._loadingDiv.appendChild(imgBack);
  57156. this._resizeLoadingUI();
  57157. window.addEventListener("resize", this._resizeLoadingUI);
  57158. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57159. document.body.appendChild(this._loadingDiv);
  57160. this._loadingDiv.style.opacity = "1";
  57161. };
  57162. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  57163. var _this = this;
  57164. if (!this._loadingDiv) {
  57165. return;
  57166. }
  57167. var onTransitionEnd = function () {
  57168. if (!_this._loadingDiv) {
  57169. return;
  57170. }
  57171. document.body.removeChild(_this._loadingDiv);
  57172. window.removeEventListener("resize", _this._resizeLoadingUI);
  57173. _this._loadingDiv = null;
  57174. };
  57175. this._loadingDiv.style.opacity = "0";
  57176. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  57177. };
  57178. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  57179. set: function (text) {
  57180. this._loadingText = text;
  57181. if (this._loadingTextDiv) {
  57182. this._loadingTextDiv.innerHTML = this._loadingText;
  57183. }
  57184. },
  57185. enumerable: true,
  57186. configurable: true
  57187. });
  57188. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  57189. get: function () {
  57190. return this._loadingDivBackgroundColor;
  57191. },
  57192. set: function (color) {
  57193. this._loadingDivBackgroundColor = color;
  57194. if (!this._loadingDiv) {
  57195. return;
  57196. }
  57197. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  57198. },
  57199. enumerable: true,
  57200. configurable: true
  57201. });
  57202. return DefaultLoadingScreen;
  57203. }());
  57204. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  57205. })(BABYLON || (BABYLON = {}));
  57206. //# sourceMappingURL=babylon.loadingScreen.js.map
  57207. var BABYLON;
  57208. (function (BABYLON) {
  57209. var SceneLoaderProgressEvent = /** @class */ (function () {
  57210. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  57211. this.lengthComputable = lengthComputable;
  57212. this.loaded = loaded;
  57213. this.total = total;
  57214. }
  57215. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  57216. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  57217. };
  57218. return SceneLoaderProgressEvent;
  57219. }());
  57220. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  57221. var SceneLoader = /** @class */ (function () {
  57222. function SceneLoader() {
  57223. }
  57224. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  57225. get: function () {
  57226. return 0;
  57227. },
  57228. enumerable: true,
  57229. configurable: true
  57230. });
  57231. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  57232. get: function () {
  57233. return 1;
  57234. },
  57235. enumerable: true,
  57236. configurable: true
  57237. });
  57238. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  57239. get: function () {
  57240. return 2;
  57241. },
  57242. enumerable: true,
  57243. configurable: true
  57244. });
  57245. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  57246. get: function () {
  57247. return 3;
  57248. },
  57249. enumerable: true,
  57250. configurable: true
  57251. });
  57252. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  57253. get: function () {
  57254. return SceneLoader._ForceFullSceneLoadingForIncremental;
  57255. },
  57256. set: function (value) {
  57257. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  57258. },
  57259. enumerable: true,
  57260. configurable: true
  57261. });
  57262. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  57263. get: function () {
  57264. return SceneLoader._ShowLoadingScreen;
  57265. },
  57266. set: function (value) {
  57267. SceneLoader._ShowLoadingScreen = value;
  57268. },
  57269. enumerable: true,
  57270. configurable: true
  57271. });
  57272. Object.defineProperty(SceneLoader, "loggingLevel", {
  57273. get: function () {
  57274. return SceneLoader._loggingLevel;
  57275. },
  57276. set: function (value) {
  57277. SceneLoader._loggingLevel = value;
  57278. },
  57279. enumerable: true,
  57280. configurable: true
  57281. });
  57282. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  57283. get: function () {
  57284. return SceneLoader._CleanBoneMatrixWeights;
  57285. },
  57286. set: function (value) {
  57287. SceneLoader._CleanBoneMatrixWeights = value;
  57288. },
  57289. enumerable: true,
  57290. configurable: true
  57291. });
  57292. SceneLoader._getDefaultPlugin = function () {
  57293. return SceneLoader._registeredPlugins[".babylon"];
  57294. };
  57295. SceneLoader._getPluginForExtension = function (extension) {
  57296. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  57297. if (registeredPlugin) {
  57298. return registeredPlugin;
  57299. }
  57300. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  57301. return SceneLoader._getDefaultPlugin();
  57302. };
  57303. SceneLoader._getPluginForDirectLoad = function (data) {
  57304. for (var extension in SceneLoader._registeredPlugins) {
  57305. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  57306. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  57307. return SceneLoader._registeredPlugins[extension];
  57308. }
  57309. }
  57310. return SceneLoader._getDefaultPlugin();
  57311. };
  57312. SceneLoader._getPluginForFilename = function (sceneFilename) {
  57313. if (sceneFilename.name) {
  57314. sceneFilename = sceneFilename.name;
  57315. }
  57316. var queryStringPosition = sceneFilename.indexOf("?");
  57317. if (queryStringPosition !== -1) {
  57318. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  57319. }
  57320. var dotPosition = sceneFilename.lastIndexOf(".");
  57321. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  57322. return SceneLoader._getPluginForExtension(extension);
  57323. };
  57324. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  57325. SceneLoader._getDirectLoad = function (sceneFilename) {
  57326. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  57327. return sceneFilename.substr(5);
  57328. }
  57329. return null;
  57330. };
  57331. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  57332. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  57333. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  57334. var plugin;
  57335. if (registeredPlugin.plugin.createPlugin) {
  57336. plugin = registeredPlugin.plugin.createPlugin();
  57337. }
  57338. else {
  57339. plugin = registeredPlugin.plugin;
  57340. }
  57341. var useArrayBuffer = registeredPlugin.isBinary;
  57342. var database;
  57343. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  57344. var dataCallback = function (data, responseURL) {
  57345. if (scene.isDisposed) {
  57346. onError("Scene has been disposed");
  57347. return;
  57348. }
  57349. scene.database = database;
  57350. onSuccess(plugin, data, responseURL);
  57351. };
  57352. var request = null;
  57353. var pluginDisposed = false;
  57354. var onDisposeObservable = plugin.onDisposeObservable;
  57355. if (onDisposeObservable) {
  57356. onDisposeObservable.add(function () {
  57357. pluginDisposed = true;
  57358. if (request) {
  57359. request.abort();
  57360. request = null;
  57361. }
  57362. onDispose();
  57363. });
  57364. }
  57365. var manifestChecked = function () {
  57366. if (pluginDisposed) {
  57367. return;
  57368. }
  57369. var url = rootUrl + sceneFilename;
  57370. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  57371. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  57372. } : undefined, database, useArrayBuffer, function (request, exception) {
  57373. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  57374. });
  57375. };
  57376. if (directLoad) {
  57377. dataCallback(directLoad);
  57378. return plugin;
  57379. }
  57380. if (rootUrl.indexOf("file:") === -1) {
  57381. if (scene.getEngine().enableOfflineSupport) {
  57382. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  57383. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  57384. }
  57385. else {
  57386. manifestChecked();
  57387. }
  57388. }
  57389. else {
  57390. var fileOrString = sceneFilename;
  57391. if (fileOrString.name) {
  57392. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  57393. }
  57394. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  57395. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  57396. }
  57397. else {
  57398. onError("Unable to find file named " + sceneFilename);
  57399. }
  57400. }
  57401. return plugin;
  57402. };
  57403. // Public functions
  57404. SceneLoader.GetPluginForExtension = function (extension) {
  57405. return SceneLoader._getPluginForExtension(extension).plugin;
  57406. };
  57407. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  57408. return !!SceneLoader._registeredPlugins[extension];
  57409. };
  57410. SceneLoader.RegisterPlugin = function (plugin) {
  57411. if (typeof plugin.extensions === "string") {
  57412. var extension = plugin.extensions;
  57413. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57414. plugin: plugin,
  57415. isBinary: false
  57416. };
  57417. }
  57418. else {
  57419. var extensions = plugin.extensions;
  57420. Object.keys(extensions).forEach(function (extension) {
  57421. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  57422. plugin: plugin,
  57423. isBinary: extensions[extension].isBinary
  57424. };
  57425. });
  57426. }
  57427. };
  57428. /**
  57429. * Import meshes into a scene
  57430. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  57431. * @param rootUrl a string that defines the root url for scene and resources
  57432. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57433. * @param scene the instance of BABYLON.Scene to append to
  57434. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  57435. * @param onProgress a callback with a progress event for each file being loaded
  57436. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57437. */
  57438. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57439. if (onSuccess === void 0) { onSuccess = null; }
  57440. if (onProgress === void 0) { onProgress = null; }
  57441. if (onError === void 0) { onError = null; }
  57442. if (pluginExtension === void 0) { pluginExtension = null; }
  57443. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57444. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57445. return null;
  57446. }
  57447. var loadingToken = {};
  57448. scene._addPendingData(loadingToken);
  57449. var disposeHandler = function () {
  57450. scene._removePendingData(loadingToken);
  57451. };
  57452. var errorHandler = function (message, exception) {
  57453. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  57454. if (onError) {
  57455. onError(scene, errorMessage, exception);
  57456. }
  57457. else {
  57458. BABYLON.Tools.Error(errorMessage);
  57459. // should the exception be thrown?
  57460. }
  57461. disposeHandler();
  57462. };
  57463. var progressHandler = onProgress ? function (event) {
  57464. try {
  57465. onProgress(event);
  57466. }
  57467. catch (e) {
  57468. errorHandler("Error in onProgress callback", e);
  57469. }
  57470. } : undefined;
  57471. var successHandler = function (meshes, particleSystems, skeletons) {
  57472. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  57473. if (onSuccess) {
  57474. try {
  57475. onSuccess(meshes, particleSystems, skeletons);
  57476. }
  57477. catch (e) {
  57478. errorHandler("Error in onSuccess callback", e);
  57479. }
  57480. }
  57481. scene._removePendingData(loadingToken);
  57482. };
  57483. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57484. if (plugin.rewriteRootURL) {
  57485. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  57486. }
  57487. if (plugin.importMesh) {
  57488. var syncedPlugin = plugin;
  57489. var meshes = new Array();
  57490. var particleSystems = new Array();
  57491. var skeletons = new Array();
  57492. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  57493. return;
  57494. }
  57495. scene.loadingPluginName = plugin.name;
  57496. successHandler(meshes, particleSystems, skeletons);
  57497. }
  57498. else {
  57499. var asyncedPlugin = plugin;
  57500. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  57501. scene.loadingPluginName = plugin.name;
  57502. successHandler(meshes, particleSystems, skeletons);
  57503. }, progressHandler, errorHandler);
  57504. }
  57505. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57506. };
  57507. /**
  57508. * Load a scene
  57509. * @param rootUrl a string that defines the root url for scene and resources
  57510. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57511. * @param engine is the instance of BABYLON.Engine to use to create the scene
  57512. * @param onSuccess a callback with the scene when import succeeds
  57513. * @param onProgress a callback with a progress event for each file being loaded
  57514. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57515. */
  57516. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  57517. if (onSuccess === void 0) { onSuccess = null; }
  57518. if (onProgress === void 0) { onProgress = null; }
  57519. if (onError === void 0) { onError = null; }
  57520. if (pluginExtension === void 0) { pluginExtension = null; }
  57521. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  57522. };
  57523. /**
  57524. * Append a scene
  57525. * @param rootUrl a string that defines the root url for scene and resources
  57526. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57527. * @param scene is the instance of BABYLON.Scene to append to
  57528. * @param onSuccess a callback with the scene when import succeeds
  57529. * @param onProgress a callback with a progress event for each file being loaded
  57530. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57531. */
  57532. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57533. if (onSuccess === void 0) { onSuccess = null; }
  57534. if (onProgress === void 0) { onProgress = null; }
  57535. if (onError === void 0) { onError = null; }
  57536. if (pluginExtension === void 0) { pluginExtension = null; }
  57537. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57538. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57539. return null;
  57540. }
  57541. if (SceneLoader.ShowLoadingScreen) {
  57542. scene.getEngine().displayLoadingUI();
  57543. }
  57544. var loadingToken = {};
  57545. scene._addPendingData(loadingToken);
  57546. var disposeHandler = function () {
  57547. scene._removePendingData(loadingToken);
  57548. scene.getEngine().hideLoadingUI();
  57549. };
  57550. var errorHandler = function (message, exception) {
  57551. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57552. if (onError) {
  57553. onError(scene, errorMessage, exception);
  57554. }
  57555. else {
  57556. BABYLON.Tools.Error(errorMessage);
  57557. // should the exception be thrown?
  57558. }
  57559. disposeHandler();
  57560. };
  57561. var progressHandler = onProgress ? function (event) {
  57562. try {
  57563. onProgress(event);
  57564. }
  57565. catch (e) {
  57566. errorHandler("Error in onProgress callback", e);
  57567. }
  57568. } : undefined;
  57569. var successHandler = function () {
  57570. if (onSuccess) {
  57571. try {
  57572. onSuccess(scene);
  57573. }
  57574. catch (e) {
  57575. errorHandler("Error in onSuccess callback", e);
  57576. }
  57577. }
  57578. scene._removePendingData(loadingToken);
  57579. };
  57580. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57581. if (plugin.load) {
  57582. var syncedPlugin = plugin;
  57583. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  57584. return;
  57585. }
  57586. scene.loadingPluginName = plugin.name;
  57587. successHandler();
  57588. }
  57589. else {
  57590. var asyncedPlugin = plugin;
  57591. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  57592. scene.loadingPluginName = plugin.name;
  57593. successHandler();
  57594. }, progressHandler, errorHandler);
  57595. }
  57596. if (SceneLoader.ShowLoadingScreen) {
  57597. scene.executeWhenReady(function () {
  57598. scene.getEngine().hideLoadingUI();
  57599. });
  57600. }
  57601. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57602. };
  57603. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57604. if (onSuccess === void 0) { onSuccess = null; }
  57605. if (onProgress === void 0) { onProgress = null; }
  57606. if (onError === void 0) { onError = null; }
  57607. if (pluginExtension === void 0) { pluginExtension = null; }
  57608. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57609. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57610. return null;
  57611. }
  57612. var loadingToken = {};
  57613. scene._addPendingData(loadingToken);
  57614. var disposeHandler = function () {
  57615. scene._removePendingData(loadingToken);
  57616. };
  57617. var errorHandler = function (message, exception) {
  57618. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57619. if (onError) {
  57620. onError(scene, errorMessage, exception);
  57621. }
  57622. else {
  57623. BABYLON.Tools.Error(errorMessage);
  57624. // should the exception be thrown?
  57625. }
  57626. disposeHandler();
  57627. };
  57628. var progressHandler = onProgress ? function (event) {
  57629. try {
  57630. onProgress(event);
  57631. }
  57632. catch (e) {
  57633. errorHandler("Error in onProgress callback", e);
  57634. }
  57635. } : undefined;
  57636. var successHandler = function (assets) {
  57637. if (onSuccess) {
  57638. try {
  57639. onSuccess(assets);
  57640. }
  57641. catch (e) {
  57642. errorHandler("Error in onSuccess callback", e);
  57643. }
  57644. }
  57645. scene._removePendingData(loadingToken);
  57646. };
  57647. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57648. if (plugin.loadAssets) {
  57649. var syncedPlugin = plugin;
  57650. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  57651. if (!assetContainer) {
  57652. return;
  57653. }
  57654. scene.loadingPluginName = plugin.name;
  57655. successHandler(assetContainer);
  57656. }
  57657. else if (plugin.loadAssetsAsync) {
  57658. var asyncedPlugin = plugin;
  57659. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  57660. if (assetContainer) {
  57661. scene.loadingPluginName = plugin.name;
  57662. successHandler(assetContainer);
  57663. }
  57664. }, progressHandler, errorHandler);
  57665. }
  57666. else {
  57667. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  57668. }
  57669. if (SceneLoader.ShowLoadingScreen) {
  57670. scene.executeWhenReady(function () {
  57671. scene.getEngine().hideLoadingUI();
  57672. });
  57673. }
  57674. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57675. };
  57676. // Flags
  57677. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  57678. SceneLoader._ShowLoadingScreen = true;
  57679. SceneLoader._CleanBoneMatrixWeights = false;
  57680. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  57681. // Members
  57682. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  57683. SceneLoader._registeredPlugins = {};
  57684. return SceneLoader;
  57685. }());
  57686. BABYLON.SceneLoader = SceneLoader;
  57687. ;
  57688. })(BABYLON || (BABYLON = {}));
  57689. //# sourceMappingURL=babylon.sceneLoader.js.map
  57690. var BABYLON;
  57691. (function (BABYLON) {
  57692. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  57693. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57694. var parsedMaterial = parsedData.materials[index];
  57695. if (parsedMaterial.id === id) {
  57696. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57697. }
  57698. }
  57699. return null;
  57700. };
  57701. var isDescendantOf = function (mesh, names, hierarchyIds) {
  57702. for (var i in names) {
  57703. if (mesh.name === names[i]) {
  57704. hierarchyIds.push(mesh.id);
  57705. return true;
  57706. }
  57707. }
  57708. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  57709. hierarchyIds.push(mesh.id);
  57710. return true;
  57711. }
  57712. return false;
  57713. };
  57714. var logOperation = function (operation, producer) {
  57715. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  57716. };
  57717. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  57718. if (addToScene === void 0) { addToScene = false; }
  57719. var container = new BABYLON.AssetContainer(scene);
  57720. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57721. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57722. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57723. // and avoid problems with multiple concurrent .babylon loads.
  57724. var log = "importScene has failed JSON parse";
  57725. try {
  57726. var parsedData = JSON.parse(data);
  57727. log = "";
  57728. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57729. var index;
  57730. var cache;
  57731. // Lights
  57732. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  57733. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  57734. var parsedLight = parsedData.lights[index];
  57735. var light = BABYLON.Light.Parse(parsedLight, scene);
  57736. if (light) {
  57737. container.lights.push(light);
  57738. log += (index === 0 ? "\n\tLights:" : "");
  57739. log += "\n\t\t" + light.toString(fullDetails);
  57740. }
  57741. }
  57742. }
  57743. // Animations
  57744. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  57745. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  57746. var parsedAnimation = parsedData.animations[index];
  57747. var animation = BABYLON.Animation.Parse(parsedAnimation);
  57748. scene.animations.push(animation);
  57749. container.animations.push(animation);
  57750. log += (index === 0 ? "\n\tAnimations:" : "");
  57751. log += "\n\t\t" + animation.toString(fullDetails);
  57752. }
  57753. }
  57754. // Materials
  57755. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  57756. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57757. var parsedMaterial = parsedData.materials[index];
  57758. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57759. container.materials.push(mat);
  57760. log += (index === 0 ? "\n\tMaterials:" : "");
  57761. log += "\n\t\t" + mat.toString(fullDetails);
  57762. }
  57763. }
  57764. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57765. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  57766. var parsedMultiMaterial = parsedData.multiMaterials[index];
  57767. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57768. container.multiMaterials.push(mmat);
  57769. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  57770. log += "\n\t\t" + mmat.toString(fullDetails);
  57771. }
  57772. }
  57773. // Morph targets
  57774. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  57775. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  57776. var managerData = _a[_i];
  57777. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  57778. }
  57779. }
  57780. // Skeletons
  57781. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57782. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  57783. var parsedSkeleton = parsedData.skeletons[index];
  57784. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57785. container.skeletons.push(skeleton);
  57786. log += (index === 0 ? "\n\tSkeletons:" : "");
  57787. log += "\n\t\t" + skeleton.toString(fullDetails);
  57788. }
  57789. }
  57790. // Geometries
  57791. var geometries = parsedData.geometries;
  57792. if (geometries !== undefined && geometries !== null) {
  57793. var addedGeometry = new Array();
  57794. // Boxes
  57795. var boxes = geometries.boxes;
  57796. if (boxes !== undefined && boxes !== null) {
  57797. for (index = 0, cache = boxes.length; index < cache; index++) {
  57798. var parsedBox = boxes[index];
  57799. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  57800. }
  57801. }
  57802. // Spheres
  57803. var spheres = geometries.spheres;
  57804. if (spheres !== undefined && spheres !== null) {
  57805. for (index = 0, cache = spheres.length; index < cache; index++) {
  57806. var parsedSphere = spheres[index];
  57807. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  57808. }
  57809. }
  57810. // Cylinders
  57811. var cylinders = geometries.cylinders;
  57812. if (cylinders !== undefined && cylinders !== null) {
  57813. for (index = 0, cache = cylinders.length; index < cache; index++) {
  57814. var parsedCylinder = cylinders[index];
  57815. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  57816. }
  57817. }
  57818. // Toruses
  57819. var toruses = geometries.toruses;
  57820. if (toruses !== undefined && toruses !== null) {
  57821. for (index = 0, cache = toruses.length; index < cache; index++) {
  57822. var parsedTorus = toruses[index];
  57823. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  57824. }
  57825. }
  57826. // Grounds
  57827. var grounds = geometries.grounds;
  57828. if (grounds !== undefined && grounds !== null) {
  57829. for (index = 0, cache = grounds.length; index < cache; index++) {
  57830. var parsedGround = grounds[index];
  57831. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  57832. }
  57833. }
  57834. // Planes
  57835. var planes = geometries.planes;
  57836. if (planes !== undefined && planes !== null) {
  57837. for (index = 0, cache = planes.length; index < cache; index++) {
  57838. var parsedPlane = planes[index];
  57839. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  57840. }
  57841. }
  57842. // TorusKnots
  57843. var torusKnots = geometries.torusKnots;
  57844. if (torusKnots !== undefined && torusKnots !== null) {
  57845. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  57846. var parsedTorusKnot = torusKnots[index];
  57847. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  57848. }
  57849. }
  57850. // VertexData
  57851. var vertexData = geometries.vertexData;
  57852. if (vertexData !== undefined && vertexData !== null) {
  57853. for (index = 0, cache = vertexData.length; index < cache; index++) {
  57854. var parsedVertexData = vertexData[index];
  57855. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  57856. }
  57857. }
  57858. addedGeometry.forEach(function (g) {
  57859. if (g) {
  57860. container.geometries.push(g);
  57861. }
  57862. });
  57863. }
  57864. // Transform nodes
  57865. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  57866. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  57867. var parsedTransformNode = parsedData.transformNodes[index];
  57868. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  57869. container.transformNodes.push(node);
  57870. }
  57871. }
  57872. // Meshes
  57873. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57874. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57875. var parsedMesh = parsedData.meshes[index];
  57876. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57877. container.meshes.push(mesh);
  57878. log += (index === 0 ? "\n\tMeshes:" : "");
  57879. log += "\n\t\t" + mesh.toString(fullDetails);
  57880. }
  57881. }
  57882. // Cameras
  57883. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  57884. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  57885. var parsedCamera = parsedData.cameras[index];
  57886. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  57887. container.cameras.push(camera);
  57888. log += (index === 0 ? "\n\tCameras:" : "");
  57889. log += "\n\t\t" + camera.toString(fullDetails);
  57890. }
  57891. }
  57892. // Browsing all the graph to connect the dots
  57893. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  57894. var camera = scene.cameras[index];
  57895. if (camera._waitingParentId) {
  57896. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  57897. camera._waitingParentId = null;
  57898. }
  57899. }
  57900. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57901. var light_1 = scene.lights[index];
  57902. if (light_1 && light_1._waitingParentId) {
  57903. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  57904. light_1._waitingParentId = null;
  57905. }
  57906. }
  57907. // Sounds
  57908. // TODO: add sound
  57909. var loadedSounds = [];
  57910. var loadedSound;
  57911. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  57912. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  57913. var parsedSound = parsedData.sounds[index];
  57914. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57915. if (!parsedSound.url)
  57916. parsedSound.url = parsedSound.name;
  57917. if (!loadedSounds[parsedSound.url]) {
  57918. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  57919. loadedSounds[parsedSound.url] = loadedSound;
  57920. container.sounds.push(loadedSound);
  57921. }
  57922. else {
  57923. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  57924. }
  57925. }
  57926. else {
  57927. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  57928. }
  57929. }
  57930. }
  57931. loadedSounds = [];
  57932. // Connect parents & children and parse actions
  57933. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  57934. var transformNode = scene.transformNodes[index];
  57935. if (transformNode._waitingParentId) {
  57936. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  57937. transformNode._waitingParentId = null;
  57938. }
  57939. }
  57940. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57941. var mesh = scene.meshes[index];
  57942. if (mesh._waitingParentId) {
  57943. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  57944. mesh._waitingParentId = null;
  57945. }
  57946. if (mesh._waitingActions) {
  57947. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  57948. mesh._waitingActions = null;
  57949. }
  57950. }
  57951. // freeze world matrix application
  57952. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57953. var currentMesh = scene.meshes[index];
  57954. if (currentMesh._waitingFreezeWorldMatrix) {
  57955. currentMesh.freezeWorldMatrix();
  57956. currentMesh._waitingFreezeWorldMatrix = null;
  57957. }
  57958. else {
  57959. currentMesh.computeWorldMatrix(true);
  57960. }
  57961. }
  57962. // Particles Systems
  57963. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57964. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57965. var parsedParticleSystem = parsedData.particleSystems[index];
  57966. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57967. container.particleSystems.push(ps);
  57968. }
  57969. }
  57970. // Lens flares
  57971. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  57972. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  57973. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  57974. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  57975. container.lensFlareSystems.push(lf);
  57976. }
  57977. }
  57978. // Shadows
  57979. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  57980. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  57981. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  57982. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  57983. container.shadowGenerators.push(sg);
  57984. }
  57985. }
  57986. // Lights exclusions / inclusions
  57987. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57988. var light_2 = scene.lights[index];
  57989. // Excluded check
  57990. if (light_2._excludedMeshesIds.length > 0) {
  57991. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  57992. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  57993. if (excludedMesh) {
  57994. light_2.excludedMeshes.push(excludedMesh);
  57995. }
  57996. }
  57997. light_2._excludedMeshesIds = [];
  57998. }
  57999. // Included check
  58000. if (light_2._includedOnlyMeshesIds.length > 0) {
  58001. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  58002. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  58003. if (includedOnlyMesh) {
  58004. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  58005. }
  58006. }
  58007. light_2._includedOnlyMeshesIds = [];
  58008. }
  58009. }
  58010. // Actions (scene)
  58011. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  58012. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  58013. }
  58014. if (!addToScene) {
  58015. container.removeAllFromScene();
  58016. }
  58017. return container;
  58018. }
  58019. catch (err) {
  58020. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  58021. if (onError) {
  58022. onError(msg, err);
  58023. }
  58024. else {
  58025. BABYLON.Tools.Log(msg);
  58026. throw err;
  58027. }
  58028. }
  58029. finally {
  58030. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58031. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58032. }
  58033. }
  58034. return null;
  58035. };
  58036. BABYLON.SceneLoader.RegisterPlugin({
  58037. name: "babylon.js",
  58038. extensions: ".babylon",
  58039. canDirectLoad: function (data) {
  58040. if (data.indexOf("babylon") !== -1) {
  58041. return true;
  58042. }
  58043. return false;
  58044. },
  58045. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  58046. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58047. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58048. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58049. // and avoid problems with multiple concurrent .babylon loads.
  58050. var log = "importMesh has failed JSON parse";
  58051. try {
  58052. var parsedData = JSON.parse(data);
  58053. log = "";
  58054. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  58055. if (!meshesNames) {
  58056. meshesNames = null;
  58057. }
  58058. else if (!Array.isArray(meshesNames)) {
  58059. meshesNames = [meshesNames];
  58060. }
  58061. var hierarchyIds = new Array();
  58062. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  58063. var loadedSkeletonsIds = [];
  58064. var loadedMaterialsIds = [];
  58065. var index;
  58066. var cache;
  58067. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  58068. var parsedMesh = parsedData.meshes[index];
  58069. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  58070. if (meshesNames !== null) {
  58071. // Remove found mesh name from list.
  58072. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  58073. }
  58074. //Geometry?
  58075. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  58076. //does the file contain geometries?
  58077. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  58078. //find the correct geometry and add it to the scene
  58079. var found = false;
  58080. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  58081. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  58082. return;
  58083. }
  58084. else {
  58085. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  58086. if (parsedGeometryData.id === parsedMesh.geometryId) {
  58087. switch (geometryType) {
  58088. case "boxes":
  58089. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  58090. break;
  58091. case "spheres":
  58092. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  58093. break;
  58094. case "cylinders":
  58095. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  58096. break;
  58097. case "toruses":
  58098. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  58099. break;
  58100. case "grounds":
  58101. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  58102. break;
  58103. case "planes":
  58104. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  58105. break;
  58106. case "torusKnots":
  58107. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  58108. break;
  58109. case "vertexData":
  58110. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  58111. break;
  58112. }
  58113. found = true;
  58114. }
  58115. });
  58116. }
  58117. });
  58118. if (found === false) {
  58119. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  58120. }
  58121. }
  58122. }
  58123. // Material ?
  58124. if (parsedMesh.materialId) {
  58125. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  58126. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  58127. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  58128. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  58129. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  58130. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  58131. var subMatId = parsedMultiMaterial.materials[matIndex];
  58132. loadedMaterialsIds.push(subMatId);
  58133. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  58134. log += "\n\tMaterial " + mat.toString(fullDetails);
  58135. }
  58136. loadedMaterialsIds.push(parsedMultiMaterial.id);
  58137. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  58138. materialFound = true;
  58139. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  58140. break;
  58141. }
  58142. }
  58143. }
  58144. if (materialFound === false) {
  58145. loadedMaterialsIds.push(parsedMesh.materialId);
  58146. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  58147. if (!mat) {
  58148. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  58149. }
  58150. else {
  58151. log += "\n\tMaterial " + mat.toString(fullDetails);
  58152. }
  58153. }
  58154. }
  58155. // Skeleton ?
  58156. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  58157. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  58158. if (skeletonAlreadyLoaded === false) {
  58159. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  58160. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  58161. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  58162. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  58163. skeletons.push(skeleton);
  58164. loadedSkeletonsIds.push(parsedSkeleton.id);
  58165. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  58166. }
  58167. }
  58168. }
  58169. }
  58170. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  58171. meshes.push(mesh);
  58172. log += "\n\tMesh " + mesh.toString(fullDetails);
  58173. }
  58174. }
  58175. // Connecting parents
  58176. var currentMesh;
  58177. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58178. currentMesh = scene.meshes[index];
  58179. if (currentMesh._waitingParentId) {
  58180. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  58181. currentMesh._waitingParentId = null;
  58182. }
  58183. }
  58184. // freeze and compute world matrix application
  58185. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  58186. currentMesh = scene.meshes[index];
  58187. if (currentMesh._waitingFreezeWorldMatrix) {
  58188. currentMesh.freezeWorldMatrix();
  58189. currentMesh._waitingFreezeWorldMatrix = null;
  58190. }
  58191. else {
  58192. currentMesh.computeWorldMatrix(true);
  58193. }
  58194. }
  58195. }
  58196. // Particles
  58197. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58198. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58199. var parsedParticleSystem = parsedData.particleSystems[index];
  58200. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  58201. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  58202. }
  58203. }
  58204. }
  58205. return true;
  58206. }
  58207. catch (err) {
  58208. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  58209. if (onError) {
  58210. onError(msg, err);
  58211. }
  58212. else {
  58213. BABYLON.Tools.Log(msg);
  58214. throw err;
  58215. }
  58216. }
  58217. finally {
  58218. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58219. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58220. }
  58221. }
  58222. return false;
  58223. },
  58224. load: function (scene, data, rootUrl, onError) {
  58225. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  58226. // when SceneLoader.debugLogging = true (default), or exception encountered.
  58227. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  58228. // and avoid problems with multiple concurrent .babylon loads.
  58229. var log = "importScene has failed JSON parse";
  58230. try {
  58231. var parsedData = JSON.parse(data);
  58232. log = "";
  58233. // Scene
  58234. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  58235. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  58236. }
  58237. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  58238. scene.autoClear = parsedData.autoClear;
  58239. }
  58240. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  58241. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  58242. }
  58243. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  58244. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  58245. }
  58246. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  58247. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  58248. }
  58249. // Fog
  58250. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  58251. scene.fogMode = parsedData.fogMode;
  58252. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  58253. scene.fogStart = parsedData.fogStart;
  58254. scene.fogEnd = parsedData.fogEnd;
  58255. scene.fogDensity = parsedData.fogDensity;
  58256. log += "\tFog mode for scene: ";
  58257. switch (scene.fogMode) {
  58258. // getters not compiling, so using hardcoded
  58259. case 1:
  58260. log += "exp\n";
  58261. break;
  58262. case 2:
  58263. log += "exp2\n";
  58264. break;
  58265. case 3:
  58266. log += "linear\n";
  58267. break;
  58268. }
  58269. }
  58270. //Physics
  58271. if (parsedData.physicsEnabled) {
  58272. var physicsPlugin;
  58273. if (parsedData.physicsEngine === "cannon") {
  58274. physicsPlugin = new BABYLON.CannonJSPlugin();
  58275. }
  58276. else if (parsedData.physicsEngine === "oimo") {
  58277. physicsPlugin = new BABYLON.OimoJSPlugin();
  58278. }
  58279. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  58280. //else - default engine, which is currently oimo
  58281. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  58282. scene.enablePhysics(physicsGravity, physicsPlugin);
  58283. }
  58284. // Metadata
  58285. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  58286. scene.metadata = parsedData.metadata;
  58287. }
  58288. //collisions, if defined. otherwise, default is true
  58289. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  58290. scene.collisionsEnabled = parsedData.collisionsEnabled;
  58291. }
  58292. scene.workerCollisions = !!parsedData.workerCollisions;
  58293. var container = loadAssets(scene, data, rootUrl, onerror, true);
  58294. if (!container) {
  58295. return false;
  58296. }
  58297. if (parsedData.autoAnimate) {
  58298. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  58299. }
  58300. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  58301. scene.setActiveCameraByID(parsedData.activeCameraID);
  58302. }
  58303. // Environment texture
  58304. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  58305. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  58306. if (parsedData.createDefaultSkybox === true) {
  58307. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  58308. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  58309. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  58310. }
  58311. }
  58312. // Finish
  58313. return true;
  58314. }
  58315. catch (err) {
  58316. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  58317. if (onError) {
  58318. onError(msg, err);
  58319. }
  58320. else {
  58321. BABYLON.Tools.Log(msg);
  58322. throw err;
  58323. }
  58324. }
  58325. finally {
  58326. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  58327. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  58328. }
  58329. }
  58330. return false;
  58331. },
  58332. loadAssets: function (scene, data, rootUrl, onError) {
  58333. var container = loadAssets(scene, data, rootUrl, onerror);
  58334. return container;
  58335. }
  58336. });
  58337. })(BABYLON || (BABYLON = {}));
  58338. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  58339. var BABYLON;
  58340. (function (BABYLON) {
  58341. var FilesInput = /** @class */ (function () {
  58342. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  58343. this.onProcessFileCallback = function () { return true; };
  58344. this._engine = engine;
  58345. this._currentScene = scene;
  58346. this._sceneLoadedCallback = sceneLoadedCallback;
  58347. this._progressCallback = progressCallback;
  58348. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  58349. this._textureLoadingCallback = textureLoadingCallback;
  58350. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  58351. this._onReloadCallback = onReloadCallback;
  58352. this._errorCallback = errorCallback;
  58353. }
  58354. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  58355. var _this = this;
  58356. if (elementToMonitor) {
  58357. this._elementToMonitor = elementToMonitor;
  58358. this._dragEnterHandler = function (e) { _this.drag(e); };
  58359. this._dragOverHandler = function (e) { _this.drag(e); };
  58360. this._dropHandler = function (e) { _this.drop(e); };
  58361. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  58362. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  58363. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  58364. }
  58365. };
  58366. FilesInput.prototype.dispose = function () {
  58367. if (!this._elementToMonitor) {
  58368. return;
  58369. }
  58370. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  58371. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  58372. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  58373. };
  58374. FilesInput.prototype.renderFunction = function () {
  58375. if (this._additionalRenderLoopLogicCallback) {
  58376. this._additionalRenderLoopLogicCallback();
  58377. }
  58378. if (this._currentScene) {
  58379. if (this._textureLoadingCallback) {
  58380. var remaining = this._currentScene.getWaitingItemsCount();
  58381. if (remaining > 0) {
  58382. this._textureLoadingCallback(remaining);
  58383. }
  58384. }
  58385. this._currentScene.render();
  58386. }
  58387. };
  58388. FilesInput.prototype.drag = function (e) {
  58389. e.stopPropagation();
  58390. e.preventDefault();
  58391. };
  58392. FilesInput.prototype.drop = function (eventDrop) {
  58393. eventDrop.stopPropagation();
  58394. eventDrop.preventDefault();
  58395. this.loadFiles(eventDrop);
  58396. };
  58397. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  58398. var _this = this;
  58399. var reader = folder.createReader();
  58400. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  58401. reader.readEntries(function (entries) {
  58402. remaining.count += entries.length;
  58403. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  58404. var entry = entries_1[_i];
  58405. if (entry.isFile) {
  58406. entry.file(function (file) {
  58407. file.correctName = relativePath + file.name;
  58408. files.push(file);
  58409. if (--remaining.count === 0) {
  58410. callback();
  58411. }
  58412. });
  58413. }
  58414. else if (entry.isDirectory) {
  58415. _this._traverseFolder(entry, files, remaining, callback);
  58416. }
  58417. }
  58418. if (--remaining.count) {
  58419. callback();
  58420. }
  58421. });
  58422. };
  58423. FilesInput.prototype._processFiles = function (files) {
  58424. for (var i = 0; i < files.length; i++) {
  58425. var name = files[i].correctName.toLowerCase();
  58426. var extension = name.split('.').pop();
  58427. if (!this.onProcessFileCallback(files[i], name, extension)) {
  58428. continue;
  58429. }
  58430. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  58431. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  58432. this._sceneFileToLoad = files[i];
  58433. }
  58434. else {
  58435. FilesInput.FilesToLoad[name] = files[i];
  58436. }
  58437. }
  58438. };
  58439. FilesInput.prototype.loadFiles = function (event) {
  58440. var _this = this;
  58441. if (this._startingProcessingFilesCallback)
  58442. this._startingProcessingFilesCallback();
  58443. // Handling data transfer via drag'n'drop
  58444. if (event && event.dataTransfer && event.dataTransfer.files) {
  58445. this._filesToLoad = event.dataTransfer.files;
  58446. }
  58447. // Handling files from input files
  58448. if (event && event.target && event.target.files) {
  58449. this._filesToLoad = event.target.files;
  58450. }
  58451. if (this._filesToLoad && this._filesToLoad.length > 0) {
  58452. var files_1 = new Array();
  58453. var folders = [];
  58454. var items = event.dataTransfer ? event.dataTransfer.items : null;
  58455. for (var i = 0; i < this._filesToLoad.length; i++) {
  58456. var fileToLoad = this._filesToLoad[i];
  58457. var name_1 = fileToLoad.name.toLowerCase();
  58458. var entry = void 0;
  58459. fileToLoad.correctName = name_1;
  58460. if (items) {
  58461. var item = items[i];
  58462. if (item.getAsEntry) {
  58463. entry = item.getAsEntry();
  58464. }
  58465. else if (item.webkitGetAsEntry) {
  58466. entry = item.webkitGetAsEntry();
  58467. }
  58468. }
  58469. if (!entry) {
  58470. files_1.push(fileToLoad);
  58471. }
  58472. else {
  58473. if (entry.isDirectory) {
  58474. folders.push(entry);
  58475. }
  58476. else {
  58477. files_1.push(fileToLoad);
  58478. }
  58479. }
  58480. }
  58481. if (folders.length === 0) {
  58482. this._processFiles(files_1);
  58483. this._processReload();
  58484. }
  58485. else {
  58486. var remaining = { count: folders.length };
  58487. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  58488. var folder = folders_1[_i];
  58489. this._traverseFolder(folder, files_1, remaining, function () {
  58490. _this._processFiles(files_1);
  58491. if (remaining.count === 0) {
  58492. _this._processReload();
  58493. }
  58494. });
  58495. }
  58496. }
  58497. }
  58498. };
  58499. FilesInput.prototype._processReload = function () {
  58500. if (this._onReloadCallback) {
  58501. this._onReloadCallback(this._sceneFileToLoad);
  58502. }
  58503. else {
  58504. this.reload();
  58505. }
  58506. };
  58507. FilesInput.prototype.reload = function () {
  58508. var _this = this;
  58509. // If a scene file has been provided
  58510. if (this._sceneFileToLoad) {
  58511. if (this._currentScene) {
  58512. if (BABYLON.Tools.errorsCount > 0) {
  58513. BABYLON.Tools.ClearLogCache();
  58514. }
  58515. this._engine.stopRenderLoop();
  58516. this._currentScene.dispose();
  58517. }
  58518. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  58519. _this._currentScene = newScene;
  58520. if (_this._sceneLoadedCallback) {
  58521. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  58522. }
  58523. // Wait for textures and shaders to be ready
  58524. _this._currentScene.executeWhenReady(function () {
  58525. _this._engine.runRenderLoop(function () {
  58526. _this.renderFunction();
  58527. });
  58528. });
  58529. }, function (progress) {
  58530. if (_this._progressCallback) {
  58531. _this._progressCallback(progress);
  58532. }
  58533. }, function (scene, message) {
  58534. _this._currentScene = scene;
  58535. if (_this._errorCallback) {
  58536. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  58537. }
  58538. });
  58539. }
  58540. else {
  58541. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  58542. }
  58543. };
  58544. FilesInput.FilesToLoad = {};
  58545. return FilesInput;
  58546. }());
  58547. BABYLON.FilesInput = FilesInput;
  58548. })(BABYLON || (BABYLON = {}));
  58549. //# sourceMappingURL=babylon.filesInput.js.map
  58550. var BABYLON;
  58551. (function (BABYLON) {
  58552. /**
  58553. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58554. * The underlying implementation relies on an associative array to ensure the best performances.
  58555. * The value can be anything including 'null' but except 'undefined'
  58556. */
  58557. var StringDictionary = /** @class */ (function () {
  58558. function StringDictionary() {
  58559. this._count = 0;
  58560. this._data = {};
  58561. }
  58562. /**
  58563. * This will clear this dictionary and copy the content from the 'source' one.
  58564. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58565. * @param source the dictionary to take the content from and copy to this dictionary
  58566. */
  58567. StringDictionary.prototype.copyFrom = function (source) {
  58568. var _this = this;
  58569. this.clear();
  58570. source.forEach(function (t, v) { return _this.add(t, v); });
  58571. };
  58572. /**
  58573. * Get a value based from its key
  58574. * @param key the given key to get the matching value from
  58575. * @return the value if found, otherwise undefined is returned
  58576. */
  58577. StringDictionary.prototype.get = function (key) {
  58578. var val = this._data[key];
  58579. if (val !== undefined) {
  58580. return val;
  58581. }
  58582. return undefined;
  58583. };
  58584. /**
  58585. * Get a value from its key or add it if it doesn't exist.
  58586. * This method will ensure you that a given key/data will be present in the dictionary.
  58587. * @param key the given key to get the matching value from
  58588. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58589. * The factory will only be invoked if there's no data for the given key.
  58590. * @return the value corresponding to the key.
  58591. */
  58592. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58593. var val = this.get(key);
  58594. if (val !== undefined) {
  58595. return val;
  58596. }
  58597. val = factory(key);
  58598. if (val) {
  58599. this.add(key, val);
  58600. }
  58601. return val;
  58602. };
  58603. /**
  58604. * Get a value from its key if present in the dictionary otherwise add it
  58605. * @param key the key to get the value from
  58606. * @param val if there's no such key/value pair in the dictionary add it with this value
  58607. * @return the value corresponding to the key
  58608. */
  58609. StringDictionary.prototype.getOrAdd = function (key, val) {
  58610. var curVal = this.get(key);
  58611. if (curVal !== undefined) {
  58612. return curVal;
  58613. }
  58614. this.add(key, val);
  58615. return val;
  58616. };
  58617. /**
  58618. * Check if there's a given key in the dictionary
  58619. * @param key the key to check for
  58620. * @return true if the key is present, false otherwise
  58621. */
  58622. StringDictionary.prototype.contains = function (key) {
  58623. return this._data[key] !== undefined;
  58624. };
  58625. /**
  58626. * Add a new key and its corresponding value
  58627. * @param key the key to add
  58628. * @param value the value corresponding to the key
  58629. * @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
  58630. */
  58631. StringDictionary.prototype.add = function (key, value) {
  58632. if (this._data[key] !== undefined) {
  58633. return false;
  58634. }
  58635. this._data[key] = value;
  58636. ++this._count;
  58637. return true;
  58638. };
  58639. StringDictionary.prototype.set = function (key, value) {
  58640. if (this._data[key] === undefined) {
  58641. return false;
  58642. }
  58643. this._data[key] = value;
  58644. return true;
  58645. };
  58646. /**
  58647. * Get the element of the given key and remove it from the dictionary
  58648. * @param key
  58649. */
  58650. StringDictionary.prototype.getAndRemove = function (key) {
  58651. var val = this.get(key);
  58652. if (val !== undefined) {
  58653. delete this._data[key];
  58654. --this._count;
  58655. return val;
  58656. }
  58657. return null;
  58658. };
  58659. /**
  58660. * Remove a key/value from the dictionary.
  58661. * @param key the key to remove
  58662. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58663. */
  58664. StringDictionary.prototype.remove = function (key) {
  58665. if (this.contains(key)) {
  58666. delete this._data[key];
  58667. --this._count;
  58668. return true;
  58669. }
  58670. return false;
  58671. };
  58672. /**
  58673. * Clear the whole content of the dictionary
  58674. */
  58675. StringDictionary.prototype.clear = function () {
  58676. this._data = {};
  58677. this._count = 0;
  58678. };
  58679. Object.defineProperty(StringDictionary.prototype, "count", {
  58680. get: function () {
  58681. return this._count;
  58682. },
  58683. enumerable: true,
  58684. configurable: true
  58685. });
  58686. /**
  58687. * Execute a callback on each key/val of the dictionary.
  58688. * Note that you can remove any element in this dictionary in the callback implementation
  58689. * @param callback the callback to execute on a given key/value pair
  58690. */
  58691. StringDictionary.prototype.forEach = function (callback) {
  58692. for (var cur in this._data) {
  58693. var val = this._data[cur];
  58694. callback(cur, val);
  58695. }
  58696. };
  58697. /**
  58698. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58699. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58700. * Note that you can remove any element in this dictionary in the callback implementation
  58701. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58702. */
  58703. StringDictionary.prototype.first = function (callback) {
  58704. for (var cur in this._data) {
  58705. var val = this._data[cur];
  58706. var res = callback(cur, val);
  58707. if (res) {
  58708. return res;
  58709. }
  58710. }
  58711. return null;
  58712. };
  58713. return StringDictionary;
  58714. }());
  58715. BABYLON.StringDictionary = StringDictionary;
  58716. })(BABYLON || (BABYLON = {}));
  58717. //# sourceMappingURL=babylon.stringDictionary.js.map
  58718. var BABYLON;
  58719. (function (BABYLON) {
  58720. var Tags = /** @class */ (function () {
  58721. function Tags() {
  58722. }
  58723. Tags.EnableFor = function (obj) {
  58724. obj._tags = obj._tags || {};
  58725. obj.hasTags = function () {
  58726. return Tags.HasTags(obj);
  58727. };
  58728. obj.addTags = function (tagsString) {
  58729. return Tags.AddTagsTo(obj, tagsString);
  58730. };
  58731. obj.removeTags = function (tagsString) {
  58732. return Tags.RemoveTagsFrom(obj, tagsString);
  58733. };
  58734. obj.matchesTagsQuery = function (tagsQuery) {
  58735. return Tags.MatchesQuery(obj, tagsQuery);
  58736. };
  58737. };
  58738. Tags.DisableFor = function (obj) {
  58739. delete obj._tags;
  58740. delete obj.hasTags;
  58741. delete obj.addTags;
  58742. delete obj.removeTags;
  58743. delete obj.matchesTagsQuery;
  58744. };
  58745. Tags.HasTags = function (obj) {
  58746. if (!obj._tags) {
  58747. return false;
  58748. }
  58749. return !BABYLON.Tools.IsEmpty(obj._tags);
  58750. };
  58751. Tags.GetTags = function (obj, asString) {
  58752. if (asString === void 0) { asString = true; }
  58753. if (!obj._tags) {
  58754. return null;
  58755. }
  58756. if (asString) {
  58757. var tagsArray = [];
  58758. for (var tag in obj._tags) {
  58759. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  58760. tagsArray.push(tag);
  58761. }
  58762. }
  58763. return tagsArray.join(" ");
  58764. }
  58765. else {
  58766. return obj._tags;
  58767. }
  58768. };
  58769. // the tags 'true' and 'false' are reserved and cannot be used as tags
  58770. // a tag cannot start with '||', '&&', and '!'
  58771. // it cannot contain whitespaces
  58772. Tags.AddTagsTo = function (obj, tagsString) {
  58773. if (!tagsString) {
  58774. return;
  58775. }
  58776. if (typeof tagsString !== "string") {
  58777. return;
  58778. }
  58779. var tags = tagsString.split(" ");
  58780. tags.forEach(function (tag, index, array) {
  58781. Tags._AddTagTo(obj, tag);
  58782. });
  58783. };
  58784. Tags._AddTagTo = function (obj, tag) {
  58785. tag = tag.trim();
  58786. if (tag === "" || tag === "true" || tag === "false") {
  58787. return;
  58788. }
  58789. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  58790. return;
  58791. }
  58792. Tags.EnableFor(obj);
  58793. obj._tags[tag] = true;
  58794. };
  58795. Tags.RemoveTagsFrom = function (obj, tagsString) {
  58796. if (!Tags.HasTags(obj)) {
  58797. return;
  58798. }
  58799. var tags = tagsString.split(" ");
  58800. for (var t in tags) {
  58801. Tags._RemoveTagFrom(obj, tags[t]);
  58802. }
  58803. };
  58804. Tags._RemoveTagFrom = function (obj, tag) {
  58805. delete obj._tags[tag];
  58806. };
  58807. Tags.MatchesQuery = function (obj, tagsQuery) {
  58808. if (tagsQuery === undefined) {
  58809. return true;
  58810. }
  58811. if (tagsQuery === "") {
  58812. return Tags.HasTags(obj);
  58813. }
  58814. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  58815. };
  58816. return Tags;
  58817. }());
  58818. BABYLON.Tags = Tags;
  58819. })(BABYLON || (BABYLON = {}));
  58820. //# sourceMappingURL=babylon.tags.js.map
  58821. var BABYLON;
  58822. (function (BABYLON) {
  58823. var AndOrNotEvaluator = /** @class */ (function () {
  58824. function AndOrNotEvaluator() {
  58825. }
  58826. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  58827. if (!query.match(/\([^\(\)]*\)/g)) {
  58828. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  58829. }
  58830. else {
  58831. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  58832. // remove parenthesis
  58833. r = r.slice(1, r.length - 1);
  58834. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  58835. });
  58836. }
  58837. if (query === "true") {
  58838. return true;
  58839. }
  58840. if (query === "false") {
  58841. return false;
  58842. }
  58843. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  58844. };
  58845. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  58846. evaluateCallback = evaluateCallback || (function (r) {
  58847. return r === "true" ? true : false;
  58848. });
  58849. var result;
  58850. var or = parenthesisContent.split("||");
  58851. for (var i in or) {
  58852. if (or.hasOwnProperty(i)) {
  58853. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  58854. var and = ori.split("&&");
  58855. if (and.length > 1) {
  58856. for (var j = 0; j < and.length; ++j) {
  58857. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  58858. if (andj !== "true" && andj !== "false") {
  58859. if (andj[0] === "!") {
  58860. result = !evaluateCallback(andj.substring(1));
  58861. }
  58862. else {
  58863. result = evaluateCallback(andj);
  58864. }
  58865. }
  58866. else {
  58867. result = andj === "true" ? true : false;
  58868. }
  58869. if (!result) {
  58870. ori = "false";
  58871. break;
  58872. }
  58873. }
  58874. }
  58875. if (result || ori === "true") {
  58876. result = true;
  58877. break;
  58878. }
  58879. // result equals false (or undefined)
  58880. if (ori !== "true" && ori !== "false") {
  58881. if (ori[0] === "!") {
  58882. result = !evaluateCallback(ori.substring(1));
  58883. }
  58884. else {
  58885. result = evaluateCallback(ori);
  58886. }
  58887. }
  58888. else {
  58889. result = ori === "true" ? true : false;
  58890. }
  58891. }
  58892. }
  58893. // the whole parenthesis scope is replaced by 'true' or 'false'
  58894. return result ? "true" : "false";
  58895. };
  58896. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  58897. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  58898. // remove whitespaces
  58899. r = r.replace(/[\s]/g, function () { return ""; });
  58900. return r.length % 2 ? "!" : "";
  58901. });
  58902. booleanString = booleanString.trim();
  58903. if (booleanString === "!true") {
  58904. booleanString = "false";
  58905. }
  58906. else if (booleanString === "!false") {
  58907. booleanString = "true";
  58908. }
  58909. return booleanString;
  58910. };
  58911. return AndOrNotEvaluator;
  58912. }());
  58913. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  58914. })(BABYLON || (BABYLON = {}));
  58915. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  58916. var BABYLON;
  58917. (function (BABYLON) {
  58918. var Database = /** @class */ (function () {
  58919. function Database(urlToScene, callbackManifestChecked) {
  58920. // Handling various flavors of prefixed version of IndexedDB
  58921. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  58922. this.callbackManifestChecked = callbackManifestChecked;
  58923. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  58924. this.db = null;
  58925. this._enableSceneOffline = false;
  58926. this._enableTexturesOffline = false;
  58927. this.manifestVersionFound = 0;
  58928. this.mustUpdateRessources = false;
  58929. this.hasReachedQuota = false;
  58930. if (!Database.IDBStorageEnabled) {
  58931. this.callbackManifestChecked(true);
  58932. }
  58933. else {
  58934. this.checkManifestFile();
  58935. }
  58936. }
  58937. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  58938. get: function () {
  58939. return this._enableSceneOffline;
  58940. },
  58941. enumerable: true,
  58942. configurable: true
  58943. });
  58944. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  58945. get: function () {
  58946. return this._enableTexturesOffline;
  58947. },
  58948. enumerable: true,
  58949. configurable: true
  58950. });
  58951. Database.prototype.checkManifestFile = function () {
  58952. var _this = this;
  58953. var noManifestFile = function () {
  58954. _this._enableSceneOffline = false;
  58955. _this._enableTexturesOffline = false;
  58956. _this.callbackManifestChecked(false);
  58957. };
  58958. var timeStampUsed = false;
  58959. var manifestURL = this.currentSceneUrl + ".manifest";
  58960. var xhr = new XMLHttpRequest();
  58961. if (navigator.onLine) {
  58962. // Adding a timestamp to by-pass browsers' cache
  58963. timeStampUsed = true;
  58964. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  58965. }
  58966. xhr.open("GET", manifestURL, true);
  58967. xhr.addEventListener("load", function () {
  58968. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  58969. try {
  58970. var manifestFile = JSON.parse(xhr.response);
  58971. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  58972. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  58973. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  58974. _this.manifestVersionFound = manifestFile.version;
  58975. }
  58976. if (_this.callbackManifestChecked) {
  58977. _this.callbackManifestChecked(true);
  58978. }
  58979. }
  58980. catch (ex) {
  58981. noManifestFile();
  58982. }
  58983. }
  58984. else {
  58985. noManifestFile();
  58986. }
  58987. }, false);
  58988. xhr.addEventListener("error", function (event) {
  58989. if (timeStampUsed) {
  58990. timeStampUsed = false;
  58991. // Let's retry without the timeStamp
  58992. // It could fail when coupled with HTML5 Offline API
  58993. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  58994. xhr.open("GET", retryManifestURL, true);
  58995. xhr.send();
  58996. }
  58997. else {
  58998. noManifestFile();
  58999. }
  59000. }, false);
  59001. try {
  59002. xhr.send();
  59003. }
  59004. catch (ex) {
  59005. BABYLON.Tools.Error("Error on XHR send request.");
  59006. this.callbackManifestChecked(false);
  59007. }
  59008. };
  59009. Database.prototype.openAsync = function (successCallback, errorCallback) {
  59010. var _this = this;
  59011. var handleError = function () {
  59012. _this.isSupported = false;
  59013. if (errorCallback)
  59014. errorCallback();
  59015. };
  59016. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  59017. // Your browser doesn't support IndexedDB
  59018. this.isSupported = false;
  59019. if (errorCallback)
  59020. errorCallback();
  59021. }
  59022. else {
  59023. // If the DB hasn't been opened or created yet
  59024. if (!this.db) {
  59025. this.hasReachedQuota = false;
  59026. this.isSupported = true;
  59027. var request = this.idbFactory.open("babylonjs", 1);
  59028. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  59029. request.onerror = function (event) {
  59030. handleError();
  59031. };
  59032. // executes when a version change transaction cannot complete due to other active transactions
  59033. request.onblocked = function (event) {
  59034. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  59035. handleError();
  59036. };
  59037. // DB has been opened successfully
  59038. request.onsuccess = function (event) {
  59039. _this.db = request.result;
  59040. successCallback();
  59041. };
  59042. // Initialization of the DB. Creating Scenes & Textures stores
  59043. request.onupgradeneeded = function (event) {
  59044. _this.db = (event.target).result;
  59045. if (_this.db) {
  59046. try {
  59047. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  59048. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  59049. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  59050. }
  59051. catch (ex) {
  59052. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  59053. handleError();
  59054. }
  59055. }
  59056. };
  59057. }
  59058. else {
  59059. if (successCallback)
  59060. successCallback();
  59061. }
  59062. }
  59063. };
  59064. Database.prototype.loadImageFromDB = function (url, image) {
  59065. var _this = this;
  59066. var completeURL = Database.ReturnFullUrlLocation(url);
  59067. var saveAndLoadImage = function () {
  59068. if (!_this.hasReachedQuota && _this.db !== null) {
  59069. // the texture is not yet in the DB, let's try to save it
  59070. _this._saveImageIntoDBAsync(completeURL, image);
  59071. }
  59072. else {
  59073. image.src = url;
  59074. }
  59075. };
  59076. if (!this.mustUpdateRessources) {
  59077. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  59078. }
  59079. else {
  59080. saveAndLoadImage();
  59081. }
  59082. };
  59083. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  59084. if (this.isSupported && this.db !== null) {
  59085. var texture;
  59086. var transaction = this.db.transaction(["textures"]);
  59087. transaction.onabort = function (event) {
  59088. image.src = url;
  59089. };
  59090. transaction.oncomplete = function (event) {
  59091. var blobTextureURL;
  59092. if (texture) {
  59093. var URL = window.URL || window.webkitURL;
  59094. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  59095. image.onerror = function () {
  59096. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  59097. image.src = url;
  59098. };
  59099. image.src = blobTextureURL;
  59100. }
  59101. else {
  59102. notInDBCallback();
  59103. }
  59104. };
  59105. var getRequest = transaction.objectStore("textures").get(url);
  59106. getRequest.onsuccess = function (event) {
  59107. texture = (event.target).result;
  59108. };
  59109. getRequest.onerror = function (event) {
  59110. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  59111. image.src = url;
  59112. };
  59113. }
  59114. else {
  59115. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59116. image.src = url;
  59117. }
  59118. };
  59119. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  59120. var _this = this;
  59121. if (this.isSupported) {
  59122. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  59123. var generateBlobUrl = function () {
  59124. var blobTextureURL;
  59125. if (blob) {
  59126. var URL = window.URL || window.webkitURL;
  59127. try {
  59128. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  59129. }
  59130. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  59131. catch (ex) {
  59132. blobTextureURL = URL.createObjectURL(blob);
  59133. }
  59134. }
  59135. if (blobTextureURL) {
  59136. image.src = blobTextureURL;
  59137. }
  59138. };
  59139. if (Database.IsUASupportingBlobStorage) {
  59140. var xhr = new XMLHttpRequest(), blob;
  59141. xhr.open("GET", url, true);
  59142. xhr.responseType = "blob";
  59143. xhr.addEventListener("load", function () {
  59144. if (xhr.status === 200 && _this.db) {
  59145. // Blob as response (XHR2)
  59146. blob = xhr.response;
  59147. var transaction = _this.db.transaction(["textures"], "readwrite");
  59148. // the transaction could abort because of a QuotaExceededError error
  59149. transaction.onabort = function (event) {
  59150. try {
  59151. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59152. var srcElement = (event.srcElement || event.target);
  59153. var error = srcElement.error;
  59154. if (error && error.name === "QuotaExceededError") {
  59155. _this.hasReachedQuota = true;
  59156. }
  59157. }
  59158. catch (ex) { }
  59159. generateBlobUrl();
  59160. };
  59161. transaction.oncomplete = function (event) {
  59162. generateBlobUrl();
  59163. };
  59164. var newTexture = { textureUrl: url, data: blob };
  59165. try {
  59166. // Put the blob into the dabase
  59167. var addRequest = transaction.objectStore("textures").put(newTexture);
  59168. addRequest.onsuccess = function (event) {
  59169. };
  59170. addRequest.onerror = function (event) {
  59171. generateBlobUrl();
  59172. };
  59173. }
  59174. catch (ex) {
  59175. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  59176. if (ex.code === 25) {
  59177. Database.IsUASupportingBlobStorage = false;
  59178. }
  59179. image.src = url;
  59180. }
  59181. }
  59182. else {
  59183. image.src = url;
  59184. }
  59185. }, false);
  59186. xhr.addEventListener("error", function (event) {
  59187. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  59188. image.src = url;
  59189. }, false);
  59190. xhr.send();
  59191. }
  59192. else {
  59193. image.src = url;
  59194. }
  59195. }
  59196. else {
  59197. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59198. image.src = url;
  59199. }
  59200. };
  59201. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  59202. var _this = this;
  59203. var updateVersion = function () {
  59204. // the version is not yet in the DB or we need to update it
  59205. _this._saveVersionIntoDBAsync(url, versionLoaded);
  59206. };
  59207. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  59208. };
  59209. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  59210. var _this = this;
  59211. if (this.isSupported && this.db) {
  59212. var version;
  59213. try {
  59214. var transaction = this.db.transaction(["versions"]);
  59215. transaction.oncomplete = function (event) {
  59216. if (version) {
  59217. // If the version in the JSON file is > than the version in DB
  59218. if (_this.manifestVersionFound > version.data) {
  59219. _this.mustUpdateRessources = true;
  59220. updateInDBCallback();
  59221. }
  59222. else {
  59223. callback(version.data);
  59224. }
  59225. }
  59226. else {
  59227. _this.mustUpdateRessources = true;
  59228. updateInDBCallback();
  59229. }
  59230. };
  59231. transaction.onabort = function (event) {
  59232. callback(-1);
  59233. };
  59234. var getRequest = transaction.objectStore("versions").get(url);
  59235. getRequest.onsuccess = function (event) {
  59236. version = (event.target).result;
  59237. };
  59238. getRequest.onerror = function (event) {
  59239. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  59240. callback(-1);
  59241. };
  59242. }
  59243. catch (ex) {
  59244. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  59245. callback(-1);
  59246. }
  59247. }
  59248. else {
  59249. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59250. callback(-1);
  59251. }
  59252. };
  59253. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  59254. var _this = this;
  59255. if (this.isSupported && !this.hasReachedQuota && this.db) {
  59256. try {
  59257. // Open a transaction to the database
  59258. var transaction = this.db.transaction(["versions"], "readwrite");
  59259. // the transaction could abort because of a QuotaExceededError error
  59260. transaction.onabort = function (event) {
  59261. try {
  59262. var error = event.srcElement['error'];
  59263. if (error && error.name === "QuotaExceededError") {
  59264. _this.hasReachedQuota = true;
  59265. }
  59266. }
  59267. catch (ex) { }
  59268. callback(-1);
  59269. };
  59270. transaction.oncomplete = function (event) {
  59271. callback(_this.manifestVersionFound);
  59272. };
  59273. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  59274. // Put the scene into the database
  59275. var addRequest = transaction.objectStore("versions").put(newVersion);
  59276. addRequest.onsuccess = function (event) {
  59277. };
  59278. addRequest.onerror = function (event) {
  59279. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  59280. };
  59281. }
  59282. catch (ex) {
  59283. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  59284. callback(-1);
  59285. }
  59286. }
  59287. else {
  59288. callback(-1);
  59289. }
  59290. };
  59291. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  59292. var _this = this;
  59293. var completeUrl = Database.ReturnFullUrlLocation(url);
  59294. var saveAndLoadFile = function () {
  59295. // the scene is not yet in the DB, let's try to save it
  59296. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  59297. };
  59298. this._checkVersionFromDB(completeUrl, function (version) {
  59299. if (version !== -1) {
  59300. if (!_this.mustUpdateRessources) {
  59301. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  59302. }
  59303. else {
  59304. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  59305. }
  59306. }
  59307. else {
  59308. if (errorCallback) {
  59309. errorCallback();
  59310. }
  59311. }
  59312. });
  59313. };
  59314. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  59315. if (this.isSupported && this.db) {
  59316. var targetStore;
  59317. if (url.indexOf(".babylon") !== -1) {
  59318. targetStore = "scenes";
  59319. }
  59320. else {
  59321. targetStore = "textures";
  59322. }
  59323. var file;
  59324. var transaction = this.db.transaction([targetStore]);
  59325. transaction.oncomplete = function (event) {
  59326. if (file) {
  59327. callback(file.data);
  59328. }
  59329. else {
  59330. notInDBCallback();
  59331. }
  59332. };
  59333. transaction.onabort = function (event) {
  59334. notInDBCallback();
  59335. };
  59336. var getRequest = transaction.objectStore(targetStore).get(url);
  59337. getRequest.onsuccess = function (event) {
  59338. file = (event.target).result;
  59339. };
  59340. getRequest.onerror = function (event) {
  59341. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  59342. notInDBCallback();
  59343. };
  59344. }
  59345. else {
  59346. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59347. callback();
  59348. }
  59349. };
  59350. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  59351. var _this = this;
  59352. if (this.isSupported) {
  59353. var targetStore;
  59354. if (url.indexOf(".babylon") !== -1) {
  59355. targetStore = "scenes";
  59356. }
  59357. else {
  59358. targetStore = "textures";
  59359. }
  59360. // Create XHR
  59361. var xhr = new XMLHttpRequest();
  59362. var fileData;
  59363. xhr.open("GET", url, true);
  59364. if (useArrayBuffer) {
  59365. xhr.responseType = "arraybuffer";
  59366. }
  59367. if (progressCallback) {
  59368. xhr.onprogress = progressCallback;
  59369. }
  59370. xhr.addEventListener("load", function () {
  59371. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  59372. // Blob as response (XHR2)
  59373. //fileData = xhr.responseText;
  59374. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  59375. if (!_this.hasReachedQuota && _this.db) {
  59376. // Open a transaction to the database
  59377. var transaction = _this.db.transaction([targetStore], "readwrite");
  59378. // the transaction could abort because of a QuotaExceededError error
  59379. transaction.onabort = function (event) {
  59380. try {
  59381. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  59382. var error = event.srcElement['error'];
  59383. if (error && error.name === "QuotaExceededError") {
  59384. _this.hasReachedQuota = true;
  59385. }
  59386. }
  59387. catch (ex) { }
  59388. callback(fileData);
  59389. };
  59390. transaction.oncomplete = function (event) {
  59391. callback(fileData);
  59392. };
  59393. var newFile;
  59394. if (targetStore === "scenes") {
  59395. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  59396. }
  59397. else {
  59398. newFile = { textureUrl: url, data: fileData };
  59399. }
  59400. try {
  59401. // Put the scene into the database
  59402. var addRequest = transaction.objectStore(targetStore).put(newFile);
  59403. addRequest.onsuccess = function (event) {
  59404. };
  59405. addRequest.onerror = function (event) {
  59406. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  59407. };
  59408. }
  59409. catch (ex) {
  59410. callback(fileData);
  59411. }
  59412. }
  59413. else {
  59414. callback(fileData);
  59415. }
  59416. }
  59417. else {
  59418. callback();
  59419. }
  59420. }, false);
  59421. xhr.addEventListener("error", function (event) {
  59422. BABYLON.Tools.Error("error on XHR request.");
  59423. callback();
  59424. }, false);
  59425. xhr.send();
  59426. }
  59427. else {
  59428. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  59429. callback();
  59430. }
  59431. };
  59432. Database.IsUASupportingBlobStorage = true;
  59433. Database.IDBStorageEnabled = true;
  59434. Database.parseURL = function (url) {
  59435. var a = document.createElement('a');
  59436. a.href = url;
  59437. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  59438. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  59439. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  59440. return absLocation;
  59441. };
  59442. Database.ReturnFullUrlLocation = function (url) {
  59443. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  59444. return (Database.parseURL(window.location.href) + url);
  59445. }
  59446. else {
  59447. return url;
  59448. }
  59449. };
  59450. return Database;
  59451. }());
  59452. BABYLON.Database = Database;
  59453. })(BABYLON || (BABYLON = {}));
  59454. //# sourceMappingURL=babylon.database.js.map
  59455. var BABYLON;
  59456. (function (BABYLON) {
  59457. var FresnelParameters = /** @class */ (function () {
  59458. function FresnelParameters() {
  59459. this._isEnabled = true;
  59460. this.leftColor = BABYLON.Color3.White();
  59461. this.rightColor = BABYLON.Color3.Black();
  59462. this.bias = 0;
  59463. this.power = 1;
  59464. }
  59465. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  59466. get: function () {
  59467. return this._isEnabled;
  59468. },
  59469. set: function (value) {
  59470. if (this._isEnabled === value) {
  59471. return;
  59472. }
  59473. this._isEnabled = value;
  59474. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  59475. },
  59476. enumerable: true,
  59477. configurable: true
  59478. });
  59479. FresnelParameters.prototype.clone = function () {
  59480. var newFresnelParameters = new FresnelParameters();
  59481. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  59482. return newFresnelParameters;
  59483. };
  59484. FresnelParameters.prototype.serialize = function () {
  59485. var serializationObject = {};
  59486. serializationObject.isEnabled = this.isEnabled;
  59487. serializationObject.leftColor = this.leftColor;
  59488. serializationObject.rightColor = this.rightColor;
  59489. serializationObject.bias = this.bias;
  59490. serializationObject.power = this.power;
  59491. return serializationObject;
  59492. };
  59493. FresnelParameters.Parse = function (parsedFresnelParameters) {
  59494. var fresnelParameters = new FresnelParameters();
  59495. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  59496. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  59497. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  59498. fresnelParameters.bias = parsedFresnelParameters.bias;
  59499. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  59500. return fresnelParameters;
  59501. };
  59502. return FresnelParameters;
  59503. }());
  59504. BABYLON.FresnelParameters = FresnelParameters;
  59505. })(BABYLON || (BABYLON = {}));
  59506. //# sourceMappingURL=babylon.fresnelParameters.js.map
  59507. var BABYLON;
  59508. (function (BABYLON) {
  59509. var MultiMaterial = /** @class */ (function (_super) {
  59510. __extends(MultiMaterial, _super);
  59511. function MultiMaterial(name, scene) {
  59512. var _this = _super.call(this, name, scene, true) || this;
  59513. scene.multiMaterials.push(_this);
  59514. _this.subMaterials = new Array();
  59515. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  59516. return _this;
  59517. }
  59518. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  59519. get: function () {
  59520. return this._subMaterials;
  59521. },
  59522. set: function (value) {
  59523. this._subMaterials = value;
  59524. this._hookArray(value);
  59525. },
  59526. enumerable: true,
  59527. configurable: true
  59528. });
  59529. MultiMaterial.prototype._hookArray = function (array) {
  59530. var _this = this;
  59531. var oldPush = array.push;
  59532. array.push = function () {
  59533. var items = [];
  59534. for (var _i = 0; _i < arguments.length; _i++) {
  59535. items[_i] = arguments[_i];
  59536. }
  59537. var result = oldPush.apply(array, items);
  59538. _this._markAllSubMeshesAsTexturesDirty();
  59539. return result;
  59540. };
  59541. var oldSplice = array.splice;
  59542. array.splice = function (index, deleteCount) {
  59543. var deleted = oldSplice.apply(array, [index, deleteCount]);
  59544. _this._markAllSubMeshesAsTexturesDirty();
  59545. return deleted;
  59546. };
  59547. };
  59548. // Properties
  59549. MultiMaterial.prototype.getSubMaterial = function (index) {
  59550. if (index < 0 || index >= this.subMaterials.length) {
  59551. return this.getScene().defaultMaterial;
  59552. }
  59553. return this.subMaterials[index];
  59554. };
  59555. MultiMaterial.prototype.getActiveTextures = function () {
  59556. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  59557. if (subMaterial) {
  59558. return subMaterial.getActiveTextures();
  59559. }
  59560. else {
  59561. return [];
  59562. }
  59563. }));
  59564. var _a;
  59565. };
  59566. // Methods
  59567. MultiMaterial.prototype.getClassName = function () {
  59568. return "MultiMaterial";
  59569. };
  59570. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  59571. for (var index = 0; index < this.subMaterials.length; index++) {
  59572. var subMaterial = this.subMaterials[index];
  59573. if (subMaterial) {
  59574. if (subMaterial.storeEffectOnSubMeshes) {
  59575. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  59576. return false;
  59577. }
  59578. continue;
  59579. }
  59580. if (!subMaterial.isReady(mesh)) {
  59581. return false;
  59582. }
  59583. }
  59584. }
  59585. return true;
  59586. };
  59587. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  59588. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  59589. for (var index = 0; index < this.subMaterials.length; index++) {
  59590. var subMaterial = null;
  59591. var current = this.subMaterials[index];
  59592. if (cloneChildren && current) {
  59593. subMaterial = current.clone(name + "-" + current.name);
  59594. }
  59595. else {
  59596. subMaterial = this.subMaterials[index];
  59597. }
  59598. newMultiMaterial.subMaterials.push(subMaterial);
  59599. }
  59600. return newMultiMaterial;
  59601. };
  59602. MultiMaterial.prototype.serialize = function () {
  59603. var serializationObject = {};
  59604. serializationObject.name = this.name;
  59605. serializationObject.id = this.id;
  59606. if (BABYLON.Tags) {
  59607. serializationObject.tags = BABYLON.Tags.GetTags(this);
  59608. }
  59609. serializationObject.materials = [];
  59610. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  59611. var subMat = this.subMaterials[matIndex];
  59612. if (subMat) {
  59613. serializationObject.materials.push(subMat.id);
  59614. }
  59615. else {
  59616. serializationObject.materials.push(null);
  59617. }
  59618. }
  59619. return serializationObject;
  59620. };
  59621. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59622. var scene = this.getScene();
  59623. if (!scene) {
  59624. return;
  59625. }
  59626. var index = scene.multiMaterials.indexOf(this);
  59627. if (index >= 0) {
  59628. scene.multiMaterials.splice(index, 1);
  59629. }
  59630. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59631. };
  59632. return MultiMaterial;
  59633. }(BABYLON.Material));
  59634. BABYLON.MultiMaterial = MultiMaterial;
  59635. })(BABYLON || (BABYLON = {}));
  59636. //# sourceMappingURL=babylon.multiMaterial.js.map
  59637. var BABYLON;
  59638. (function (BABYLON) {
  59639. var FreeCameraTouchInput = /** @class */ (function () {
  59640. function FreeCameraTouchInput() {
  59641. this._offsetX = null;
  59642. this._offsetY = null;
  59643. this._pointerPressed = new Array();
  59644. this.touchAngularSensibility = 200000.0;
  59645. this.touchMoveSensibility = 250.0;
  59646. }
  59647. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  59648. var _this = this;
  59649. var previousPosition = null;
  59650. if (this._pointerInput === undefined) {
  59651. this._onLostFocus = function (evt) {
  59652. _this._offsetX = null;
  59653. _this._offsetY = null;
  59654. };
  59655. this._pointerInput = function (p, s) {
  59656. var evt = p.event;
  59657. if (evt.pointerType === "mouse") {
  59658. return;
  59659. }
  59660. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  59661. if (!noPreventDefault) {
  59662. evt.preventDefault();
  59663. }
  59664. _this._pointerPressed.push(evt.pointerId);
  59665. if (_this._pointerPressed.length !== 1) {
  59666. return;
  59667. }
  59668. previousPosition = {
  59669. x: evt.clientX,
  59670. y: evt.clientY
  59671. };
  59672. }
  59673. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  59674. if (!noPreventDefault) {
  59675. evt.preventDefault();
  59676. }
  59677. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59678. if (index === -1) {
  59679. return;
  59680. }
  59681. _this._pointerPressed.splice(index, 1);
  59682. if (index != 0) {
  59683. return;
  59684. }
  59685. previousPosition = null;
  59686. _this._offsetX = null;
  59687. _this._offsetY = null;
  59688. }
  59689. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  59690. if (!noPreventDefault) {
  59691. evt.preventDefault();
  59692. }
  59693. if (!previousPosition) {
  59694. return;
  59695. }
  59696. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59697. if (index != 0) {
  59698. return;
  59699. }
  59700. _this._offsetX = evt.clientX - previousPosition.x;
  59701. _this._offsetY = -(evt.clientY - previousPosition.y);
  59702. }
  59703. };
  59704. }
  59705. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  59706. if (this._onLostFocus) {
  59707. element.addEventListener("blur", this._onLostFocus);
  59708. }
  59709. };
  59710. FreeCameraTouchInput.prototype.detachControl = function (element) {
  59711. if (this._pointerInput && element) {
  59712. if (this._observer) {
  59713. this.camera.getScene().onPointerObservable.remove(this._observer);
  59714. this._observer = null;
  59715. }
  59716. if (this._onLostFocus) {
  59717. element.removeEventListener("blur", this._onLostFocus);
  59718. this._onLostFocus = null;
  59719. }
  59720. this._pointerPressed = [];
  59721. this._offsetX = null;
  59722. this._offsetY = null;
  59723. }
  59724. };
  59725. FreeCameraTouchInput.prototype.checkInputs = function () {
  59726. if (this._offsetX && this._offsetY) {
  59727. var camera = this.camera;
  59728. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  59729. if (this._pointerPressed.length > 1) {
  59730. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  59731. }
  59732. else {
  59733. var speed = camera._computeLocalCameraSpeed();
  59734. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  59735. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  59736. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  59737. }
  59738. }
  59739. };
  59740. FreeCameraTouchInput.prototype.getClassName = function () {
  59741. return "FreeCameraTouchInput";
  59742. };
  59743. FreeCameraTouchInput.prototype.getSimpleName = function () {
  59744. return "touch";
  59745. };
  59746. __decorate([
  59747. BABYLON.serialize()
  59748. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  59749. __decorate([
  59750. BABYLON.serialize()
  59751. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  59752. return FreeCameraTouchInput;
  59753. }());
  59754. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  59755. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  59756. })(BABYLON || (BABYLON = {}));
  59757. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  59758. var BABYLON;
  59759. (function (BABYLON) {
  59760. // We're mainly based on the logic defined into the FreeCamera code
  59761. var TouchCamera = /** @class */ (function (_super) {
  59762. __extends(TouchCamera, _super);
  59763. //-- end properties for backward compatibility for inputs
  59764. function TouchCamera(name, position, scene) {
  59765. var _this = _super.call(this, name, position, scene) || this;
  59766. _this.inputs.addTouch();
  59767. _this._setupInputs();
  59768. return _this;
  59769. }
  59770. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  59771. //-- Begin properties for backward compatibility for inputs
  59772. get: function () {
  59773. var touch = this.inputs.attached["touch"];
  59774. if (touch)
  59775. return touch.touchAngularSensibility;
  59776. return 0;
  59777. },
  59778. set: function (value) {
  59779. var touch = this.inputs.attached["touch"];
  59780. if (touch)
  59781. touch.touchAngularSensibility = value;
  59782. },
  59783. enumerable: true,
  59784. configurable: true
  59785. });
  59786. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  59787. get: function () {
  59788. var touch = this.inputs.attached["touch"];
  59789. if (touch)
  59790. return touch.touchMoveSensibility;
  59791. return 0;
  59792. },
  59793. set: function (value) {
  59794. var touch = this.inputs.attached["touch"];
  59795. if (touch)
  59796. touch.touchMoveSensibility = value;
  59797. },
  59798. enumerable: true,
  59799. configurable: true
  59800. });
  59801. TouchCamera.prototype.getClassName = function () {
  59802. return "TouchCamera";
  59803. };
  59804. TouchCamera.prototype._setupInputs = function () {
  59805. var mouse = this.inputs.attached["mouse"];
  59806. if (mouse) {
  59807. mouse.touchEnabled = false;
  59808. }
  59809. };
  59810. return TouchCamera;
  59811. }(BABYLON.FreeCamera));
  59812. BABYLON.TouchCamera = TouchCamera;
  59813. })(BABYLON || (BABYLON = {}));
  59814. //# sourceMappingURL=babylon.touchCamera.js.map
  59815. var BABYLON;
  59816. (function (BABYLON) {
  59817. var ProceduralTexture = /** @class */ (function (_super) {
  59818. __extends(ProceduralTexture, _super);
  59819. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  59820. if (fallbackTexture === void 0) { fallbackTexture = null; }
  59821. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59822. if (isCube === void 0) { isCube = false; }
  59823. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59824. _this.isCube = isCube;
  59825. _this.isEnabled = true;
  59826. _this._currentRefreshId = -1;
  59827. _this._refreshRate = 1;
  59828. _this._vertexBuffers = {};
  59829. _this._uniforms = new Array();
  59830. _this._samplers = new Array();
  59831. _this._textures = {};
  59832. _this._floats = {};
  59833. _this._floatsArrays = {};
  59834. _this._colors3 = {};
  59835. _this._colors4 = {};
  59836. _this._vectors2 = {};
  59837. _this._vectors3 = {};
  59838. _this._matrices = {};
  59839. _this._fallbackTextureUsed = false;
  59840. scene._proceduralTextures.push(_this);
  59841. _this._engine = scene.getEngine();
  59842. _this.name = name;
  59843. _this.isRenderTarget = true;
  59844. _this._size = size;
  59845. _this._generateMipMaps = generateMipMaps;
  59846. _this.setFragment(fragment);
  59847. _this._fallbackTexture = fallbackTexture;
  59848. if (isCube) {
  59849. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  59850. _this.setFloat("face", 0);
  59851. }
  59852. else {
  59853. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  59854. }
  59855. // VBO
  59856. var vertices = [];
  59857. vertices.push(1, 1);
  59858. vertices.push(-1, 1);
  59859. vertices.push(-1, -1);
  59860. vertices.push(1, -1);
  59861. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59862. _this._createIndexBuffer();
  59863. return _this;
  59864. }
  59865. ProceduralTexture.prototype._createIndexBuffer = function () {
  59866. var engine = this._engine;
  59867. // Indices
  59868. var indices = [];
  59869. indices.push(0);
  59870. indices.push(1);
  59871. indices.push(2);
  59872. indices.push(0);
  59873. indices.push(2);
  59874. indices.push(3);
  59875. this._indexBuffer = engine.createIndexBuffer(indices);
  59876. };
  59877. ProceduralTexture.prototype._rebuild = function () {
  59878. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59879. if (vb) {
  59880. vb._rebuild();
  59881. }
  59882. this._createIndexBuffer();
  59883. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59884. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59885. }
  59886. };
  59887. ProceduralTexture.prototype.reset = function () {
  59888. if (this._effect === undefined) {
  59889. return;
  59890. }
  59891. var engine = this._engine;
  59892. engine._releaseEffect(this._effect);
  59893. };
  59894. ProceduralTexture.prototype.isReady = function () {
  59895. var _this = this;
  59896. var engine = this._engine;
  59897. var shaders;
  59898. if (!this._fragment) {
  59899. return false;
  59900. }
  59901. if (this._fallbackTextureUsed) {
  59902. return true;
  59903. }
  59904. if (this._fragment.fragmentElement !== undefined) {
  59905. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  59906. }
  59907. else {
  59908. shaders = { vertex: "procedural", fragment: this._fragment };
  59909. }
  59910. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  59911. _this.releaseInternalTexture();
  59912. if (_this._fallbackTexture) {
  59913. _this._texture = _this._fallbackTexture._texture;
  59914. if (_this._texture) {
  59915. _this._texture.incrementReferences();
  59916. }
  59917. }
  59918. _this._fallbackTextureUsed = true;
  59919. });
  59920. return this._effect.isReady();
  59921. };
  59922. ProceduralTexture.prototype.resetRefreshCounter = function () {
  59923. this._currentRefreshId = -1;
  59924. };
  59925. ProceduralTexture.prototype.setFragment = function (fragment) {
  59926. this._fragment = fragment;
  59927. };
  59928. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  59929. get: function () {
  59930. return this._refreshRate;
  59931. },
  59932. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59933. set: function (value) {
  59934. this._refreshRate = value;
  59935. this.resetRefreshCounter();
  59936. },
  59937. enumerable: true,
  59938. configurable: true
  59939. });
  59940. ProceduralTexture.prototype._shouldRender = function () {
  59941. if (!this.isEnabled || !this.isReady() || !this._texture) {
  59942. return false;
  59943. }
  59944. if (this._fallbackTextureUsed) {
  59945. return false;
  59946. }
  59947. if (this._currentRefreshId === -1) {
  59948. this._currentRefreshId = 1;
  59949. return true;
  59950. }
  59951. if (this.refreshRate === this._currentRefreshId) {
  59952. this._currentRefreshId = 1;
  59953. return true;
  59954. }
  59955. this._currentRefreshId++;
  59956. return false;
  59957. };
  59958. ProceduralTexture.prototype.getRenderSize = function () {
  59959. return this._size;
  59960. };
  59961. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  59962. if (this._fallbackTextureUsed) {
  59963. return;
  59964. }
  59965. this.releaseInternalTexture();
  59966. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  59967. };
  59968. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  59969. if (this._uniforms.indexOf(uniformName) === -1) {
  59970. this._uniforms.push(uniformName);
  59971. }
  59972. };
  59973. ProceduralTexture.prototype.setTexture = function (name, texture) {
  59974. if (this._samplers.indexOf(name) === -1) {
  59975. this._samplers.push(name);
  59976. }
  59977. this._textures[name] = texture;
  59978. return this;
  59979. };
  59980. ProceduralTexture.prototype.setFloat = function (name, value) {
  59981. this._checkUniform(name);
  59982. this._floats[name] = value;
  59983. return this;
  59984. };
  59985. ProceduralTexture.prototype.setFloats = function (name, value) {
  59986. this._checkUniform(name);
  59987. this._floatsArrays[name] = value;
  59988. return this;
  59989. };
  59990. ProceduralTexture.prototype.setColor3 = function (name, value) {
  59991. this._checkUniform(name);
  59992. this._colors3[name] = value;
  59993. return this;
  59994. };
  59995. ProceduralTexture.prototype.setColor4 = function (name, value) {
  59996. this._checkUniform(name);
  59997. this._colors4[name] = value;
  59998. return this;
  59999. };
  60000. ProceduralTexture.prototype.setVector2 = function (name, value) {
  60001. this._checkUniform(name);
  60002. this._vectors2[name] = value;
  60003. return this;
  60004. };
  60005. ProceduralTexture.prototype.setVector3 = function (name, value) {
  60006. this._checkUniform(name);
  60007. this._vectors3[name] = value;
  60008. return this;
  60009. };
  60010. ProceduralTexture.prototype.setMatrix = function (name, value) {
  60011. this._checkUniform(name);
  60012. this._matrices[name] = value;
  60013. return this;
  60014. };
  60015. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60016. var scene = this.getScene();
  60017. if (!scene) {
  60018. return;
  60019. }
  60020. var engine = this._engine;
  60021. // Render
  60022. engine.enableEffect(this._effect);
  60023. engine.setState(false);
  60024. // Texture
  60025. for (var name in this._textures) {
  60026. this._effect.setTexture(name, this._textures[name]);
  60027. }
  60028. // Float
  60029. for (name in this._floats) {
  60030. this._effect.setFloat(name, this._floats[name]);
  60031. }
  60032. // Floats
  60033. for (name in this._floatsArrays) {
  60034. this._effect.setArray(name, this._floatsArrays[name]);
  60035. }
  60036. // Color3
  60037. for (name in this._colors3) {
  60038. this._effect.setColor3(name, this._colors3[name]);
  60039. }
  60040. // Color4
  60041. for (name in this._colors4) {
  60042. var color = this._colors4[name];
  60043. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60044. }
  60045. // Vector2
  60046. for (name in this._vectors2) {
  60047. this._effect.setVector2(name, this._vectors2[name]);
  60048. }
  60049. // Vector3
  60050. for (name in this._vectors3) {
  60051. this._effect.setVector3(name, this._vectors3[name]);
  60052. }
  60053. // Matrix
  60054. for (name in this._matrices) {
  60055. this._effect.setMatrix(name, this._matrices[name]);
  60056. }
  60057. if (!this._texture) {
  60058. return;
  60059. }
  60060. if (this.isCube) {
  60061. for (var face = 0; face < 6; face++) {
  60062. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  60063. // VBOs
  60064. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60065. this._effect.setFloat("face", face);
  60066. // Clear
  60067. engine.clear(scene.clearColor, true, true, true);
  60068. // Draw order
  60069. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60070. // Mipmaps
  60071. if (face === 5) {
  60072. engine.generateMipMapsForCubemap(this._texture);
  60073. }
  60074. }
  60075. }
  60076. else {
  60077. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  60078. // VBOs
  60079. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60080. // Clear
  60081. engine.clear(scene.clearColor, true, true, true);
  60082. // Draw order
  60083. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  60084. }
  60085. // Unbind
  60086. engine.unBindFramebuffer(this._texture, this.isCube);
  60087. if (this.onGenerated) {
  60088. this.onGenerated();
  60089. }
  60090. };
  60091. ProceduralTexture.prototype.clone = function () {
  60092. var textureSize = this.getSize();
  60093. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  60094. // Base texture
  60095. newTexture.hasAlpha = this.hasAlpha;
  60096. newTexture.level = this.level;
  60097. // RenderTarget Texture
  60098. newTexture.coordinatesMode = this.coordinatesMode;
  60099. return newTexture;
  60100. };
  60101. ProceduralTexture.prototype.dispose = function () {
  60102. var scene = this.getScene();
  60103. if (!scene) {
  60104. return;
  60105. }
  60106. var index = scene._proceduralTextures.indexOf(this);
  60107. if (index >= 0) {
  60108. scene._proceduralTextures.splice(index, 1);
  60109. }
  60110. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60111. if (vertexBuffer) {
  60112. vertexBuffer.dispose();
  60113. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60114. }
  60115. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  60116. this._indexBuffer = null;
  60117. }
  60118. _super.prototype.dispose.call(this);
  60119. };
  60120. return ProceduralTexture;
  60121. }(BABYLON.Texture));
  60122. BABYLON.ProceduralTexture = ProceduralTexture;
  60123. })(BABYLON || (BABYLON = {}));
  60124. //# sourceMappingURL=babylon.proceduralTexture.js.map
  60125. var BABYLON;
  60126. (function (BABYLON) {
  60127. var CustomProceduralTexture = /** @class */ (function (_super) {
  60128. __extends(CustomProceduralTexture, _super);
  60129. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  60130. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  60131. _this._animate = true;
  60132. _this._time = 0;
  60133. _this._texturePath = texturePath;
  60134. //Try to load json
  60135. _this.loadJson(texturePath);
  60136. _this.refreshRate = 1;
  60137. return _this;
  60138. }
  60139. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  60140. var _this = this;
  60141. var noConfigFile = function () {
  60142. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  60143. try {
  60144. _this.setFragment(_this._texturePath);
  60145. }
  60146. catch (ex) {
  60147. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  60148. }
  60149. };
  60150. var configFileUrl = jsonUrl + "/config.json";
  60151. var xhr = new XMLHttpRequest();
  60152. xhr.open("GET", configFileUrl, true);
  60153. xhr.addEventListener("load", function () {
  60154. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60155. try {
  60156. _this._config = JSON.parse(xhr.response);
  60157. _this.updateShaderUniforms();
  60158. _this.updateTextures();
  60159. _this.setFragment(_this._texturePath + "/custom");
  60160. _this._animate = _this._config.animate;
  60161. _this.refreshRate = _this._config.refreshrate;
  60162. }
  60163. catch (ex) {
  60164. noConfigFile();
  60165. }
  60166. }
  60167. else {
  60168. noConfigFile();
  60169. }
  60170. }, false);
  60171. xhr.addEventListener("error", function () {
  60172. noConfigFile();
  60173. }, false);
  60174. try {
  60175. xhr.send();
  60176. }
  60177. catch (ex) {
  60178. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  60179. }
  60180. };
  60181. CustomProceduralTexture.prototype.isReady = function () {
  60182. if (!_super.prototype.isReady.call(this)) {
  60183. return false;
  60184. }
  60185. for (var name in this._textures) {
  60186. var texture = this._textures[name];
  60187. if (!texture.isReady()) {
  60188. return false;
  60189. }
  60190. }
  60191. return true;
  60192. };
  60193. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  60194. var scene = this.getScene();
  60195. if (this._animate && scene) {
  60196. this._time += scene.getAnimationRatio() * 0.03;
  60197. this.updateShaderUniforms();
  60198. }
  60199. _super.prototype.render.call(this, useCameraPostProcess);
  60200. };
  60201. CustomProceduralTexture.prototype.updateTextures = function () {
  60202. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  60203. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  60204. }
  60205. };
  60206. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  60207. if (this._config) {
  60208. for (var j = 0; j < this._config.uniforms.length; j++) {
  60209. var uniform = this._config.uniforms[j];
  60210. switch (uniform.type) {
  60211. case "float":
  60212. this.setFloat(uniform.name, uniform.value);
  60213. break;
  60214. case "color3":
  60215. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  60216. break;
  60217. case "color4":
  60218. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  60219. break;
  60220. case "vector2":
  60221. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  60222. break;
  60223. case "vector3":
  60224. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  60225. break;
  60226. }
  60227. }
  60228. }
  60229. this.setFloat("time", this._time);
  60230. };
  60231. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  60232. get: function () {
  60233. return this._animate;
  60234. },
  60235. set: function (value) {
  60236. this._animate = value;
  60237. },
  60238. enumerable: true,
  60239. configurable: true
  60240. });
  60241. return CustomProceduralTexture;
  60242. }(BABYLON.ProceduralTexture));
  60243. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  60244. })(BABYLON || (BABYLON = {}));
  60245. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  60246. var BABYLON;
  60247. (function (BABYLON) {
  60248. var FreeCameraGamepadInput = /** @class */ (function () {
  60249. function FreeCameraGamepadInput() {
  60250. this.gamepadAngularSensibility = 200;
  60251. this.gamepadMoveSensibility = 40;
  60252. // private members
  60253. this._cameraTransform = BABYLON.Matrix.Identity();
  60254. this._deltaTransform = BABYLON.Vector3.Zero();
  60255. this._vector3 = BABYLON.Vector3.Zero();
  60256. this._vector2 = BABYLON.Vector2.Zero();
  60257. }
  60258. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60259. var _this = this;
  60260. var manager = this.camera.getScene().gamepadManager;
  60261. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60262. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60263. // prioritize XBOX gamepads.
  60264. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60265. _this.gamepad = gamepad;
  60266. }
  60267. }
  60268. });
  60269. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60270. if (_this.gamepad === gamepad) {
  60271. _this.gamepad = null;
  60272. }
  60273. });
  60274. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60275. };
  60276. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  60277. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60278. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60279. this.gamepad = null;
  60280. };
  60281. FreeCameraGamepadInput.prototype.checkInputs = function () {
  60282. if (this.gamepad && this.gamepad.leftStick) {
  60283. var camera = this.camera;
  60284. var LSValues = this.gamepad.leftStick;
  60285. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  60286. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60287. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  60288. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  60289. var RSValues = this.gamepad.rightStick;
  60290. if (RSValues) {
  60291. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  60292. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  60293. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  60294. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  60295. }
  60296. else {
  60297. RSValues = { x: 0, y: 0 };
  60298. }
  60299. if (!camera.rotationQuaternion) {
  60300. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  60301. }
  60302. else {
  60303. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  60304. }
  60305. var speed = camera._computeLocalCameraSpeed() * 50.0;
  60306. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  60307. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  60308. camera.cameraDirection.addInPlace(this._deltaTransform);
  60309. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  60310. camera.cameraRotation.addInPlace(this._vector2);
  60311. }
  60312. };
  60313. FreeCameraGamepadInput.prototype.getClassName = function () {
  60314. return "FreeCameraGamepadInput";
  60315. };
  60316. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  60317. return "gamepad";
  60318. };
  60319. __decorate([
  60320. BABYLON.serialize()
  60321. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  60322. __decorate([
  60323. BABYLON.serialize()
  60324. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60325. return FreeCameraGamepadInput;
  60326. }());
  60327. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  60328. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  60329. })(BABYLON || (BABYLON = {}));
  60330. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  60331. var BABYLON;
  60332. (function (BABYLON) {
  60333. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  60334. function ArcRotateCameraGamepadInput() {
  60335. this.gamepadRotationSensibility = 80;
  60336. this.gamepadMoveSensibility = 40;
  60337. }
  60338. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  60339. var _this = this;
  60340. var manager = this.camera.getScene().gamepadManager;
  60341. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  60342. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  60343. // prioritize XBOX gamepads.
  60344. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  60345. _this.gamepad = gamepad;
  60346. }
  60347. }
  60348. });
  60349. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  60350. if (_this.gamepad === gamepad) {
  60351. _this.gamepad = null;
  60352. }
  60353. });
  60354. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  60355. };
  60356. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  60357. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  60358. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  60359. this.gamepad = null;
  60360. };
  60361. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  60362. if (this.gamepad) {
  60363. var camera = this.camera;
  60364. var RSValues = this.gamepad.rightStick;
  60365. if (RSValues) {
  60366. if (RSValues.x != 0) {
  60367. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  60368. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  60369. camera.inertialAlphaOffset += normalizedRX;
  60370. }
  60371. }
  60372. if (RSValues.y != 0) {
  60373. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  60374. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  60375. camera.inertialBetaOffset += normalizedRY;
  60376. }
  60377. }
  60378. }
  60379. var LSValues = this.gamepad.leftStick;
  60380. if (LSValues && LSValues.y != 0) {
  60381. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  60382. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  60383. this.camera.inertialRadiusOffset -= normalizedLY;
  60384. }
  60385. }
  60386. }
  60387. };
  60388. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  60389. return "ArcRotateCameraGamepadInput";
  60390. };
  60391. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  60392. return "gamepad";
  60393. };
  60394. __decorate([
  60395. BABYLON.serialize()
  60396. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  60397. __decorate([
  60398. BABYLON.serialize()
  60399. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  60400. return ArcRotateCameraGamepadInput;
  60401. }());
  60402. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  60403. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  60404. })(BABYLON || (BABYLON = {}));
  60405. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  60406. var BABYLON;
  60407. (function (BABYLON) {
  60408. var GamepadManager = /** @class */ (function () {
  60409. function GamepadManager(_scene) {
  60410. var _this = this;
  60411. this._scene = _scene;
  60412. this._babylonGamepads = [];
  60413. this._oneGamepadConnected = false;
  60414. this._isMonitoring = false;
  60415. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  60416. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60417. this._gamepadEventSupported = false;
  60418. }
  60419. else {
  60420. this._gamepadEventSupported = 'GamepadEvent' in window;
  60421. this._gamepadSupport = (navigator.getGamepads ||
  60422. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  60423. }
  60424. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  60425. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  60426. for (var i in _this._babylonGamepads) {
  60427. var gamepad = _this._babylonGamepads[i];
  60428. if (gamepad && gamepad._isConnected) {
  60429. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  60430. }
  60431. }
  60432. });
  60433. this._onGamepadConnectedEvent = function (evt) {
  60434. var gamepad = evt.gamepad;
  60435. if (gamepad.index in _this._babylonGamepads) {
  60436. if (_this._babylonGamepads[gamepad.index].isConnected) {
  60437. return;
  60438. }
  60439. }
  60440. var newGamepad;
  60441. if (_this._babylonGamepads[gamepad.index]) {
  60442. newGamepad = _this._babylonGamepads[gamepad.index];
  60443. newGamepad.browserGamepad = gamepad;
  60444. newGamepad._isConnected = true;
  60445. }
  60446. else {
  60447. newGamepad = _this._addNewGamepad(gamepad);
  60448. }
  60449. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60450. _this._startMonitoringGamepads();
  60451. };
  60452. this._onGamepadDisconnectedEvent = function (evt) {
  60453. var gamepad = evt.gamepad;
  60454. // Remove the gamepad from the list of gamepads to monitor.
  60455. for (var i in _this._babylonGamepads) {
  60456. if (_this._babylonGamepads[i].index === gamepad.index) {
  60457. var disconnectedGamepad = _this._babylonGamepads[i];
  60458. disconnectedGamepad._isConnected = false;
  60459. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  60460. break;
  60461. }
  60462. }
  60463. };
  60464. if (this._gamepadSupport) {
  60465. //first add already-connected gamepads
  60466. this._updateGamepadObjects();
  60467. if (this._babylonGamepads.length) {
  60468. this._startMonitoringGamepads();
  60469. }
  60470. // Checking if the gamepad connected event is supported (like in Firefox)
  60471. if (this._gamepadEventSupported) {
  60472. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  60473. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  60474. }
  60475. else {
  60476. this._startMonitoringGamepads();
  60477. }
  60478. }
  60479. }
  60480. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  60481. get: function () {
  60482. return this._babylonGamepads;
  60483. },
  60484. enumerable: true,
  60485. configurable: true
  60486. });
  60487. GamepadManager.prototype.getGamepadByType = function (type) {
  60488. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  60489. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  60490. var gamepad = _a[_i];
  60491. if (gamepad && gamepad.type === type) {
  60492. return gamepad;
  60493. }
  60494. }
  60495. return null;
  60496. };
  60497. GamepadManager.prototype.dispose = function () {
  60498. if (this._gamepadEventSupported) {
  60499. if (this._onGamepadConnectedEvent) {
  60500. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  60501. }
  60502. if (this._onGamepadDisconnectedEvent) {
  60503. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  60504. }
  60505. this._onGamepadConnectedEvent = null;
  60506. this._onGamepadDisconnectedEvent = null;
  60507. }
  60508. this._babylonGamepads.forEach(function (gamepad) {
  60509. gamepad.dispose();
  60510. });
  60511. this.onGamepadConnectedObservable.clear();
  60512. this.onGamepadDisconnectedObservable.clear();
  60513. this._oneGamepadConnected = false;
  60514. this._stopMonitoringGamepads();
  60515. this._babylonGamepads = [];
  60516. };
  60517. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  60518. if (!this._oneGamepadConnected) {
  60519. this._oneGamepadConnected = true;
  60520. }
  60521. var newGamepad;
  60522. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  60523. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  60524. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  60525. }
  60526. else if (gamepad.pose) {
  60527. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  60528. }
  60529. else {
  60530. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  60531. }
  60532. this._babylonGamepads[newGamepad.index] = newGamepad;
  60533. return newGamepad;
  60534. };
  60535. GamepadManager.prototype._startMonitoringGamepads = function () {
  60536. if (!this._isMonitoring) {
  60537. this._isMonitoring = true;
  60538. //back-comp
  60539. if (!this._scene) {
  60540. this._checkGamepadsStatus();
  60541. }
  60542. }
  60543. };
  60544. GamepadManager.prototype._stopMonitoringGamepads = function () {
  60545. this._isMonitoring = false;
  60546. };
  60547. GamepadManager.prototype._checkGamepadsStatus = function () {
  60548. var _this = this;
  60549. // Hack to be compatible Chrome
  60550. this._updateGamepadObjects();
  60551. for (var i in this._babylonGamepads) {
  60552. var gamepad = this._babylonGamepads[i];
  60553. if (!gamepad || !gamepad.isConnected) {
  60554. continue;
  60555. }
  60556. gamepad.update();
  60557. }
  60558. if (this._isMonitoring && !this._scene) {
  60559. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  60560. }
  60561. };
  60562. // This function is called only on Chrome, which does not properly support
  60563. // connection/disconnection events and forces you to recopy again the gamepad object
  60564. GamepadManager.prototype._updateGamepadObjects = function () {
  60565. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  60566. for (var i = 0; i < gamepads.length; i++) {
  60567. if (gamepads[i]) {
  60568. if (!this._babylonGamepads[gamepads[i].index]) {
  60569. var newGamepad = this._addNewGamepad(gamepads[i]);
  60570. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60571. }
  60572. else {
  60573. // Forced to copy again this object for Chrome for unknown reason
  60574. this._babylonGamepads[i].browserGamepad = gamepads[i];
  60575. if (!this._babylonGamepads[i].isConnected) {
  60576. this._babylonGamepads[i]._isConnected = true;
  60577. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  60578. }
  60579. }
  60580. }
  60581. }
  60582. };
  60583. return GamepadManager;
  60584. }());
  60585. BABYLON.GamepadManager = GamepadManager;
  60586. })(BABYLON || (BABYLON = {}));
  60587. //# sourceMappingURL=babylon.gamepadManager.js.map
  60588. var BABYLON;
  60589. (function (BABYLON) {
  60590. var StickValues = /** @class */ (function () {
  60591. function StickValues(x, y) {
  60592. this.x = x;
  60593. this.y = y;
  60594. }
  60595. return StickValues;
  60596. }());
  60597. BABYLON.StickValues = StickValues;
  60598. var Gamepad = /** @class */ (function () {
  60599. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  60600. if (leftStickX === void 0) { leftStickX = 0; }
  60601. if (leftStickY === void 0) { leftStickY = 1; }
  60602. if (rightStickX === void 0) { rightStickX = 2; }
  60603. if (rightStickY === void 0) { rightStickY = 3; }
  60604. this.id = id;
  60605. this.index = index;
  60606. this.browserGamepad = browserGamepad;
  60607. this._isConnected = true;
  60608. this._invertLeftStickY = false;
  60609. this.type = Gamepad.GAMEPAD;
  60610. this._leftStickAxisX = leftStickX;
  60611. this._leftStickAxisY = leftStickY;
  60612. this._rightStickAxisX = rightStickX;
  60613. this._rightStickAxisY = rightStickY;
  60614. if (this.browserGamepad.axes.length >= 2) {
  60615. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60616. }
  60617. if (this.browserGamepad.axes.length >= 4) {
  60618. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60619. }
  60620. }
  60621. Object.defineProperty(Gamepad.prototype, "isConnected", {
  60622. get: function () {
  60623. return this._isConnected;
  60624. },
  60625. enumerable: true,
  60626. configurable: true
  60627. });
  60628. Gamepad.prototype.onleftstickchanged = function (callback) {
  60629. this._onleftstickchanged = callback;
  60630. };
  60631. Gamepad.prototype.onrightstickchanged = function (callback) {
  60632. this._onrightstickchanged = callback;
  60633. };
  60634. Object.defineProperty(Gamepad.prototype, "leftStick", {
  60635. get: function () {
  60636. return this._leftStick;
  60637. },
  60638. set: function (newValues) {
  60639. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  60640. this._onleftstickchanged(newValues);
  60641. }
  60642. this._leftStick = newValues;
  60643. },
  60644. enumerable: true,
  60645. configurable: true
  60646. });
  60647. Object.defineProperty(Gamepad.prototype, "rightStick", {
  60648. get: function () {
  60649. return this._rightStick;
  60650. },
  60651. set: function (newValues) {
  60652. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  60653. this._onrightstickchanged(newValues);
  60654. }
  60655. this._rightStick = newValues;
  60656. },
  60657. enumerable: true,
  60658. configurable: true
  60659. });
  60660. Gamepad.prototype.update = function () {
  60661. if (this._leftStick) {
  60662. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60663. if (this._invertLeftStickY) {
  60664. this.leftStick.y *= -1;
  60665. }
  60666. }
  60667. if (this._rightStick) {
  60668. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60669. }
  60670. };
  60671. Gamepad.prototype.dispose = function () {
  60672. };
  60673. Gamepad.GAMEPAD = 0;
  60674. Gamepad.GENERIC = 1;
  60675. Gamepad.XBOX = 2;
  60676. Gamepad.POSE_ENABLED = 3;
  60677. return Gamepad;
  60678. }());
  60679. BABYLON.Gamepad = Gamepad;
  60680. var GenericPad = /** @class */ (function (_super) {
  60681. __extends(GenericPad, _super);
  60682. function GenericPad(id, index, browserGamepad) {
  60683. var _this = _super.call(this, id, index, browserGamepad) || this;
  60684. _this.onButtonDownObservable = new BABYLON.Observable();
  60685. _this.onButtonUpObservable = new BABYLON.Observable();
  60686. _this.type = Gamepad.GENERIC;
  60687. _this._buttons = new Array(browserGamepad.buttons.length);
  60688. return _this;
  60689. }
  60690. GenericPad.prototype.onbuttondown = function (callback) {
  60691. this._onbuttondown = callback;
  60692. };
  60693. GenericPad.prototype.onbuttonup = function (callback) {
  60694. this._onbuttonup = callback;
  60695. };
  60696. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  60697. if (newValue !== currentValue) {
  60698. if (newValue === 1) {
  60699. if (this._onbuttondown) {
  60700. this._onbuttondown(buttonIndex);
  60701. }
  60702. this.onButtonDownObservable.notifyObservers(buttonIndex);
  60703. }
  60704. if (newValue === 0) {
  60705. if (this._onbuttonup) {
  60706. this._onbuttonup(buttonIndex);
  60707. }
  60708. this.onButtonUpObservable.notifyObservers(buttonIndex);
  60709. }
  60710. }
  60711. return newValue;
  60712. };
  60713. GenericPad.prototype.update = function () {
  60714. _super.prototype.update.call(this);
  60715. for (var index = 0; index < this._buttons.length; index++) {
  60716. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  60717. }
  60718. };
  60719. GenericPad.prototype.dispose = function () {
  60720. _super.prototype.dispose.call(this);
  60721. this.onButtonDownObservable.clear();
  60722. this.onButtonUpObservable.clear();
  60723. };
  60724. return GenericPad;
  60725. }(Gamepad));
  60726. BABYLON.GenericPad = GenericPad;
  60727. })(BABYLON || (BABYLON = {}));
  60728. //# sourceMappingURL=babylon.gamepad.js.map
  60729. var BABYLON;
  60730. (function (BABYLON) {
  60731. var Xbox360Button;
  60732. (function (Xbox360Button) {
  60733. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  60734. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  60735. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  60736. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  60737. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  60738. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  60739. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  60740. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  60741. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  60742. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  60743. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  60744. var Xbox360Dpad;
  60745. (function (Xbox360Dpad) {
  60746. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  60747. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  60748. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  60749. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  60750. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  60751. var Xbox360Pad = /** @class */ (function (_super) {
  60752. __extends(Xbox360Pad, _super);
  60753. function Xbox360Pad(id, index, gamepad, xboxOne) {
  60754. if (xboxOne === void 0) { xboxOne = false; }
  60755. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  60756. _this._leftTrigger = 0;
  60757. _this._rightTrigger = 0;
  60758. _this.onButtonDownObservable = new BABYLON.Observable();
  60759. _this.onButtonUpObservable = new BABYLON.Observable();
  60760. _this.onPadDownObservable = new BABYLON.Observable();
  60761. _this.onPadUpObservable = new BABYLON.Observable();
  60762. _this._buttonA = 0;
  60763. _this._buttonB = 0;
  60764. _this._buttonX = 0;
  60765. _this._buttonY = 0;
  60766. _this._buttonBack = 0;
  60767. _this._buttonStart = 0;
  60768. _this._buttonLB = 0;
  60769. _this._buttonRB = 0;
  60770. _this._buttonLeftStick = 0;
  60771. _this._buttonRightStick = 0;
  60772. _this._dPadUp = 0;
  60773. _this._dPadDown = 0;
  60774. _this._dPadLeft = 0;
  60775. _this._dPadRight = 0;
  60776. _this._isXboxOnePad = false;
  60777. _this.type = BABYLON.Gamepad.XBOX;
  60778. _this._isXboxOnePad = xboxOne;
  60779. return _this;
  60780. }
  60781. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  60782. this._onlefttriggerchanged = callback;
  60783. };
  60784. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  60785. this._onrighttriggerchanged = callback;
  60786. };
  60787. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  60788. get: function () {
  60789. return this._leftTrigger;
  60790. },
  60791. set: function (newValue) {
  60792. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  60793. this._onlefttriggerchanged(newValue);
  60794. }
  60795. this._leftTrigger = newValue;
  60796. },
  60797. enumerable: true,
  60798. configurable: true
  60799. });
  60800. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  60801. get: function () {
  60802. return this._rightTrigger;
  60803. },
  60804. set: function (newValue) {
  60805. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  60806. this._onrighttriggerchanged(newValue);
  60807. }
  60808. this._rightTrigger = newValue;
  60809. },
  60810. enumerable: true,
  60811. configurable: true
  60812. });
  60813. Xbox360Pad.prototype.onbuttondown = function (callback) {
  60814. this._onbuttondown = callback;
  60815. };
  60816. Xbox360Pad.prototype.onbuttonup = function (callback) {
  60817. this._onbuttonup = callback;
  60818. };
  60819. Xbox360Pad.prototype.ondpaddown = function (callback) {
  60820. this._ondpaddown = callback;
  60821. };
  60822. Xbox360Pad.prototype.ondpadup = function (callback) {
  60823. this._ondpadup = callback;
  60824. };
  60825. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  60826. if (newValue !== currentValue) {
  60827. if (newValue === 1) {
  60828. if (this._onbuttondown) {
  60829. this._onbuttondown(buttonType);
  60830. }
  60831. this.onButtonDownObservable.notifyObservers(buttonType);
  60832. }
  60833. if (newValue === 0) {
  60834. if (this._onbuttonup) {
  60835. this._onbuttonup(buttonType);
  60836. }
  60837. this.onButtonUpObservable.notifyObservers(buttonType);
  60838. }
  60839. }
  60840. return newValue;
  60841. };
  60842. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  60843. if (newValue !== currentValue) {
  60844. if (newValue === 1) {
  60845. if (this._ondpaddown) {
  60846. this._ondpaddown(buttonType);
  60847. }
  60848. this.onPadDownObservable.notifyObservers(buttonType);
  60849. }
  60850. if (newValue === 0) {
  60851. if (this._ondpadup) {
  60852. this._ondpadup(buttonType);
  60853. }
  60854. this.onPadUpObservable.notifyObservers(buttonType);
  60855. }
  60856. }
  60857. return newValue;
  60858. };
  60859. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  60860. get: function () {
  60861. return this._buttonA;
  60862. },
  60863. set: function (value) {
  60864. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  60865. },
  60866. enumerable: true,
  60867. configurable: true
  60868. });
  60869. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  60870. get: function () {
  60871. return this._buttonB;
  60872. },
  60873. set: function (value) {
  60874. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  60875. },
  60876. enumerable: true,
  60877. configurable: true
  60878. });
  60879. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  60880. get: function () {
  60881. return this._buttonX;
  60882. },
  60883. set: function (value) {
  60884. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  60885. },
  60886. enumerable: true,
  60887. configurable: true
  60888. });
  60889. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  60890. get: function () {
  60891. return this._buttonY;
  60892. },
  60893. set: function (value) {
  60894. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  60895. },
  60896. enumerable: true,
  60897. configurable: true
  60898. });
  60899. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  60900. get: function () {
  60901. return this._buttonStart;
  60902. },
  60903. set: function (value) {
  60904. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  60905. },
  60906. enumerable: true,
  60907. configurable: true
  60908. });
  60909. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  60910. get: function () {
  60911. return this._buttonBack;
  60912. },
  60913. set: function (value) {
  60914. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  60915. },
  60916. enumerable: true,
  60917. configurable: true
  60918. });
  60919. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  60920. get: function () {
  60921. return this._buttonLB;
  60922. },
  60923. set: function (value) {
  60924. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  60925. },
  60926. enumerable: true,
  60927. configurable: true
  60928. });
  60929. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  60930. get: function () {
  60931. return this._buttonRB;
  60932. },
  60933. set: function (value) {
  60934. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  60935. },
  60936. enumerable: true,
  60937. configurable: true
  60938. });
  60939. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  60940. get: function () {
  60941. return this._buttonLeftStick;
  60942. },
  60943. set: function (value) {
  60944. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  60945. },
  60946. enumerable: true,
  60947. configurable: true
  60948. });
  60949. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  60950. get: function () {
  60951. return this._buttonRightStick;
  60952. },
  60953. set: function (value) {
  60954. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  60955. },
  60956. enumerable: true,
  60957. configurable: true
  60958. });
  60959. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  60960. get: function () {
  60961. return this._dPadUp;
  60962. },
  60963. set: function (value) {
  60964. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  60965. },
  60966. enumerable: true,
  60967. configurable: true
  60968. });
  60969. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  60970. get: function () {
  60971. return this._dPadDown;
  60972. },
  60973. set: function (value) {
  60974. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  60975. },
  60976. enumerable: true,
  60977. configurable: true
  60978. });
  60979. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  60980. get: function () {
  60981. return this._dPadLeft;
  60982. },
  60983. set: function (value) {
  60984. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  60985. },
  60986. enumerable: true,
  60987. configurable: true
  60988. });
  60989. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  60990. get: function () {
  60991. return this._dPadRight;
  60992. },
  60993. set: function (value) {
  60994. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  60995. },
  60996. enumerable: true,
  60997. configurable: true
  60998. });
  60999. Xbox360Pad.prototype.update = function () {
  61000. _super.prototype.update.call(this);
  61001. if (this._isXboxOnePad) {
  61002. this.buttonA = this.browserGamepad.buttons[0].value;
  61003. this.buttonB = this.browserGamepad.buttons[1].value;
  61004. this.buttonX = this.browserGamepad.buttons[2].value;
  61005. this.buttonY = this.browserGamepad.buttons[3].value;
  61006. this.buttonLB = this.browserGamepad.buttons[4].value;
  61007. this.buttonRB = this.browserGamepad.buttons[5].value;
  61008. this.leftTrigger = this.browserGamepad.axes[2];
  61009. this.rightTrigger = this.browserGamepad.axes[5];
  61010. this.buttonBack = this.browserGamepad.buttons[9].value;
  61011. this.buttonStart = this.browserGamepad.buttons[8].value;
  61012. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  61013. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  61014. this.dPadUp = this.browserGamepad.buttons[11].value;
  61015. this.dPadDown = this.browserGamepad.buttons[12].value;
  61016. this.dPadLeft = this.browserGamepad.buttons[13].value;
  61017. this.dPadRight = this.browserGamepad.buttons[14].value;
  61018. }
  61019. else {
  61020. this.buttonA = this.browserGamepad.buttons[0].value;
  61021. this.buttonB = this.browserGamepad.buttons[1].value;
  61022. this.buttonX = this.browserGamepad.buttons[2].value;
  61023. this.buttonY = this.browserGamepad.buttons[3].value;
  61024. this.buttonLB = this.browserGamepad.buttons[4].value;
  61025. this.buttonRB = this.browserGamepad.buttons[5].value;
  61026. this.leftTrigger = this.browserGamepad.buttons[6].value;
  61027. this.rightTrigger = this.browserGamepad.buttons[7].value;
  61028. this.buttonBack = this.browserGamepad.buttons[8].value;
  61029. this.buttonStart = this.browserGamepad.buttons[9].value;
  61030. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  61031. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  61032. this.dPadUp = this.browserGamepad.buttons[12].value;
  61033. this.dPadDown = this.browserGamepad.buttons[13].value;
  61034. this.dPadLeft = this.browserGamepad.buttons[14].value;
  61035. this.dPadRight = this.browserGamepad.buttons[15].value;
  61036. }
  61037. };
  61038. Xbox360Pad.prototype.dispose = function () {
  61039. _super.prototype.dispose.call(this);
  61040. this.onButtonDownObservable.clear();
  61041. this.onButtonUpObservable.clear();
  61042. this.onPadDownObservable.clear();
  61043. this.onPadUpObservable.clear();
  61044. };
  61045. return Xbox360Pad;
  61046. }(BABYLON.Gamepad));
  61047. BABYLON.Xbox360Pad = Xbox360Pad;
  61048. })(BABYLON || (BABYLON = {}));
  61049. //# sourceMappingURL=babylon.xboxGamepad.js.map
  61050. var BABYLON;
  61051. (function (BABYLON) {
  61052. var PoseEnabledControllerType;
  61053. (function (PoseEnabledControllerType) {
  61054. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  61055. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  61056. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  61057. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  61058. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  61059. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  61060. var PoseEnabledControllerHelper = /** @class */ (function () {
  61061. function PoseEnabledControllerHelper() {
  61062. }
  61063. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  61064. // Oculus Touch
  61065. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  61066. return new BABYLON.OculusTouchController(vrGamepad);
  61067. }
  61068. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  61069. return new BABYLON.WindowsMotionController(vrGamepad);
  61070. }
  61071. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  61072. return new BABYLON.ViveController(vrGamepad);
  61073. }
  61074. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  61075. return new BABYLON.GearVRController(vrGamepad);
  61076. }
  61077. else {
  61078. return new BABYLON.GenericController(vrGamepad);
  61079. }
  61080. };
  61081. return PoseEnabledControllerHelper;
  61082. }());
  61083. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  61084. var PoseEnabledController = /** @class */ (function (_super) {
  61085. __extends(PoseEnabledController, _super);
  61086. function PoseEnabledController(browserGamepad) {
  61087. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  61088. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  61089. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  61090. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  61091. // Represents device position and rotation in babylon space
  61092. _this.devicePosition = BABYLON.Vector3.Zero();
  61093. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61094. _this.deviceScaleFactor = 1;
  61095. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  61096. _this._deviceToWorld = BABYLON.Matrix.Identity();
  61097. _this._workingMatrix = BABYLON.Matrix.Identity();
  61098. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  61099. _this.controllerType = PoseEnabledControllerType.GENERIC;
  61100. _this.position = BABYLON.Vector3.Zero();
  61101. _this.rotationQuaternion = new BABYLON.Quaternion();
  61102. _this._calculatedPosition = BABYLON.Vector3.Zero();
  61103. _this._calculatedRotation = new BABYLON.Quaternion();
  61104. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  61105. return _this;
  61106. }
  61107. PoseEnabledController.prototype.update = function () {
  61108. _super.prototype.update.call(this);
  61109. var pose = this.browserGamepad.pose;
  61110. this.updateFromDevice(pose);
  61111. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  61112. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  61113. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  61114. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  61115. if (this._mesh) {
  61116. this._mesh.position.copyFrom(this.devicePosition);
  61117. if (this._mesh.rotationQuaternion) {
  61118. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61119. }
  61120. }
  61121. };
  61122. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  61123. if (poseData) {
  61124. this.rawPose = poseData;
  61125. if (poseData.position) {
  61126. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  61127. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  61128. this._deviceRoomPosition.z *= -1;
  61129. }
  61130. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  61131. this._calculatedPosition.addInPlace(this.position);
  61132. }
  61133. var pose = this.rawPose;
  61134. if (poseData.orientation && pose.orientation) {
  61135. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  61136. if (this._mesh) {
  61137. if (this._mesh.getScene().useRightHandedSystem) {
  61138. this._deviceRoomRotationQuaternion.z *= -1;
  61139. this._deviceRoomRotationQuaternion.w *= -1;
  61140. }
  61141. else {
  61142. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  61143. }
  61144. }
  61145. // if the camera is set, rotate to the camera's rotation
  61146. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  61147. }
  61148. }
  61149. };
  61150. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  61151. if (this._mesh) {
  61152. this._mesh.parent = null;
  61153. }
  61154. this._mesh = mesh;
  61155. if (this._poseControlledCamera) {
  61156. this._mesh.parent = this._poseControlledCamera;
  61157. }
  61158. if (!this._mesh.rotationQuaternion) {
  61159. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  61160. }
  61161. };
  61162. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  61163. this._poseControlledCamera = camera;
  61164. if (this._mesh) {
  61165. this._mesh.parent = this._poseControlledCamera;
  61166. }
  61167. };
  61168. PoseEnabledController.prototype.dispose = function () {
  61169. if (this._mesh) {
  61170. this._mesh.dispose();
  61171. }
  61172. this._mesh = null;
  61173. _super.prototype.dispose.call(this);
  61174. };
  61175. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  61176. get: function () {
  61177. return this._mesh;
  61178. },
  61179. enumerable: true,
  61180. configurable: true
  61181. });
  61182. PoseEnabledController.prototype.getForwardRay = function (length) {
  61183. if (length === void 0) { length = 100; }
  61184. if (!this.mesh) {
  61185. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  61186. }
  61187. var m = this.mesh.getWorldMatrix();
  61188. var origin = m.getTranslation();
  61189. var forward = new BABYLON.Vector3(0, 0, -1);
  61190. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61191. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61192. return new BABYLON.Ray(origin, direction, length);
  61193. };
  61194. return PoseEnabledController;
  61195. }(BABYLON.Gamepad));
  61196. BABYLON.PoseEnabledController = PoseEnabledController;
  61197. })(BABYLON || (BABYLON = {}));
  61198. //# sourceMappingURL=babylon.poseEnabledController.js.map
  61199. var BABYLON;
  61200. (function (BABYLON) {
  61201. var WebVRController = /** @class */ (function (_super) {
  61202. __extends(WebVRController, _super);
  61203. function WebVRController(vrGamepad) {
  61204. var _this = _super.call(this, vrGamepad) || this;
  61205. // Observables
  61206. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  61207. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  61208. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  61209. _this.onPadStateChangedObservable = new BABYLON.Observable();
  61210. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  61211. _this.pad = { x: 0, y: 0 };
  61212. // avoid GC, store state in a tmp object
  61213. _this._changes = {
  61214. pressChanged: false,
  61215. touchChanged: false,
  61216. valueChanged: false,
  61217. changed: false
  61218. };
  61219. _this._buttons = new Array(vrGamepad.buttons.length);
  61220. _this.hand = vrGamepad.hand;
  61221. return _this;
  61222. }
  61223. WebVRController.prototype.onButtonStateChange = function (callback) {
  61224. this._onButtonStateChange = callback;
  61225. };
  61226. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  61227. get: function () {
  61228. return this._defaultModel;
  61229. },
  61230. enumerable: true,
  61231. configurable: true
  61232. });
  61233. WebVRController.prototype.update = function () {
  61234. _super.prototype.update.call(this);
  61235. for (var index = 0; index < this._buttons.length; index++) {
  61236. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  61237. }
  61238. ;
  61239. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  61240. this.pad.x = this.leftStick.x;
  61241. this.pad.y = this.leftStick.y;
  61242. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  61243. }
  61244. };
  61245. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  61246. if (!newState) {
  61247. newState = {
  61248. pressed: false,
  61249. touched: false,
  61250. value: 0
  61251. };
  61252. }
  61253. if (!currentState) {
  61254. this._buttons[buttonIndex] = {
  61255. pressed: newState.pressed,
  61256. touched: newState.touched,
  61257. value: newState.value
  61258. };
  61259. return;
  61260. }
  61261. this._checkChanges(newState, currentState);
  61262. if (this._changes.changed) {
  61263. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  61264. this.handleButtonChange(buttonIndex, newState, this._changes);
  61265. }
  61266. this._buttons[buttonIndex].pressed = newState.pressed;
  61267. this._buttons[buttonIndex].touched = newState.touched;
  61268. // oculus triggers are never 0, thou not touched.
  61269. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  61270. };
  61271. WebVRController.prototype._checkChanges = function (newState, currentState) {
  61272. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  61273. this._changes.touchChanged = newState.touched !== currentState.touched;
  61274. this._changes.valueChanged = newState.value !== currentState.value;
  61275. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  61276. return this._changes;
  61277. };
  61278. WebVRController.prototype.dispose = function () {
  61279. _super.prototype.dispose.call(this);
  61280. this.onTriggerStateChangedObservable.clear();
  61281. this.onMainButtonStateChangedObservable.clear();
  61282. this.onSecondaryButtonStateChangedObservable.clear();
  61283. this.onPadStateChangedObservable.clear();
  61284. this.onPadValuesChangedObservable.clear();
  61285. };
  61286. return WebVRController;
  61287. }(BABYLON.PoseEnabledController));
  61288. BABYLON.WebVRController = WebVRController;
  61289. })(BABYLON || (BABYLON = {}));
  61290. //# sourceMappingURL=babylon.webVRController.js.map
  61291. var BABYLON;
  61292. (function (BABYLON) {
  61293. var OculusTouchController = /** @class */ (function (_super) {
  61294. __extends(OculusTouchController, _super);
  61295. function OculusTouchController(vrGamepad) {
  61296. var _this = _super.call(this, vrGamepad) || this;
  61297. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  61298. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  61299. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  61300. return _this;
  61301. }
  61302. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61303. var _this = this;
  61304. var meshName;
  61305. // Hand
  61306. if (this.hand === 'left') {
  61307. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  61308. }
  61309. else {
  61310. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  61311. }
  61312. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  61313. /*
  61314. Parent Mesh name: oculus_touch_left
  61315. - body
  61316. - trigger
  61317. - thumbstick
  61318. - grip
  61319. - button_y
  61320. - button_x
  61321. - button_enter
  61322. */
  61323. _this._defaultModel = newMeshes[1];
  61324. _this.attachToMesh(_this._defaultModel);
  61325. if (meshLoaded) {
  61326. meshLoaded(_this._defaultModel);
  61327. }
  61328. });
  61329. };
  61330. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  61331. // helper getters for left and right hand.
  61332. get: function () {
  61333. if (this.hand === 'right') {
  61334. return this.onMainButtonStateChangedObservable;
  61335. }
  61336. else {
  61337. throw new Error('No A button on left hand');
  61338. }
  61339. },
  61340. enumerable: true,
  61341. configurable: true
  61342. });
  61343. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  61344. get: function () {
  61345. if (this.hand === 'right') {
  61346. return this.onSecondaryButtonStateChangedObservable;
  61347. }
  61348. else {
  61349. throw new Error('No B button on left hand');
  61350. }
  61351. },
  61352. enumerable: true,
  61353. configurable: true
  61354. });
  61355. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  61356. get: function () {
  61357. if (this.hand === 'left') {
  61358. return this.onMainButtonStateChangedObservable;
  61359. }
  61360. else {
  61361. throw new Error('No X button on right hand');
  61362. }
  61363. },
  61364. enumerable: true,
  61365. configurable: true
  61366. });
  61367. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  61368. get: function () {
  61369. if (this.hand === 'left') {
  61370. return this.onSecondaryButtonStateChangedObservable;
  61371. }
  61372. else {
  61373. throw new Error('No Y button on right hand');
  61374. }
  61375. },
  61376. enumerable: true,
  61377. configurable: true
  61378. });
  61379. /*
  61380. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  61381. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  61382. 2) secondary trigger (same)
  61383. 3) A (right) X (left), touch, pressed = value
  61384. 4) B / Y
  61385. 5) thumb rest
  61386. */
  61387. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61388. var notifyObject = state; //{ state: state, changes: changes };
  61389. var triggerDirection = this.hand === 'right' ? -1 : 1;
  61390. switch (buttonIdx) {
  61391. case 0:
  61392. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61393. return;
  61394. case 1:// index trigger
  61395. if (this._defaultModel) {
  61396. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  61397. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  61398. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  61399. }
  61400. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61401. return;
  61402. case 2:// secondary trigger
  61403. if (this._defaultModel) {
  61404. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  61405. }
  61406. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  61407. return;
  61408. case 3:
  61409. if (this._defaultModel) {
  61410. if (notifyObject.pressed) {
  61411. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  61412. }
  61413. else {
  61414. (this._defaultModel.getChildren()[1]).position.y = 0;
  61415. }
  61416. }
  61417. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61418. return;
  61419. case 4:
  61420. if (this._defaultModel) {
  61421. if (notifyObject.pressed) {
  61422. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61423. }
  61424. else {
  61425. (this._defaultModel.getChildren()[2]).position.y = 0;
  61426. }
  61427. }
  61428. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61429. return;
  61430. case 5:
  61431. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  61432. return;
  61433. }
  61434. };
  61435. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  61436. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  61437. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  61438. return OculusTouchController;
  61439. }(BABYLON.WebVRController));
  61440. BABYLON.OculusTouchController = OculusTouchController;
  61441. })(BABYLON || (BABYLON = {}));
  61442. //# sourceMappingURL=babylon.oculusTouchController.js.map
  61443. var BABYLON;
  61444. (function (BABYLON) {
  61445. var ViveController = /** @class */ (function (_super) {
  61446. __extends(ViveController, _super);
  61447. function ViveController(vrGamepad) {
  61448. var _this = _super.call(this, vrGamepad) || this;
  61449. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  61450. _this._invertLeftStickY = true;
  61451. return _this;
  61452. }
  61453. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61454. var _this = this;
  61455. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  61456. /*
  61457. Parent Mesh name: ViveWand
  61458. - body
  61459. - r_gripper
  61460. - l_gripper
  61461. - menu_button
  61462. - system_button
  61463. - trackpad
  61464. - trigger
  61465. - LED
  61466. */
  61467. _this._defaultModel = newMeshes[1];
  61468. _this.attachToMesh(_this._defaultModel);
  61469. if (meshLoaded) {
  61470. meshLoaded(_this._defaultModel);
  61471. }
  61472. });
  61473. };
  61474. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  61475. get: function () {
  61476. return this.onMainButtonStateChangedObservable;
  61477. },
  61478. enumerable: true,
  61479. configurable: true
  61480. });
  61481. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  61482. get: function () {
  61483. return this.onMainButtonStateChangedObservable;
  61484. },
  61485. enumerable: true,
  61486. configurable: true
  61487. });
  61488. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  61489. get: function () {
  61490. return this.onSecondaryButtonStateChangedObservable;
  61491. },
  61492. enumerable: true,
  61493. configurable: true
  61494. });
  61495. /**
  61496. * Vive mapping:
  61497. * 0: touchpad
  61498. * 1: trigger
  61499. * 2: left AND right buttons
  61500. * 3: menu button
  61501. */
  61502. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61503. var notifyObject = state; //{ state: state, changes: changes };
  61504. switch (buttonIdx) {
  61505. case 0:
  61506. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61507. return;
  61508. case 1:// index trigger
  61509. if (this._defaultModel) {
  61510. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  61511. }
  61512. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61513. return;
  61514. case 2:// left AND right button
  61515. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61516. return;
  61517. case 3:
  61518. if (this._defaultModel) {
  61519. if (notifyObject.pressed) {
  61520. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61521. }
  61522. else {
  61523. (this._defaultModel.getChildren()[2]).position.y = 0;
  61524. }
  61525. }
  61526. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61527. return;
  61528. }
  61529. };
  61530. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  61531. ViveController.MODEL_FILENAME = 'wand.babylon';
  61532. return ViveController;
  61533. }(BABYLON.WebVRController));
  61534. BABYLON.ViveController = ViveController;
  61535. })(BABYLON || (BABYLON = {}));
  61536. //# sourceMappingURL=babylon.viveController.js.map
  61537. var BABYLON;
  61538. (function (BABYLON) {
  61539. var GenericController = /** @class */ (function (_super) {
  61540. __extends(GenericController, _super);
  61541. function GenericController(vrGamepad) {
  61542. return _super.call(this, vrGamepad) || this;
  61543. }
  61544. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61545. var _this = this;
  61546. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  61547. _this._defaultModel = newMeshes[1];
  61548. _this.attachToMesh(_this._defaultModel);
  61549. if (meshLoaded) {
  61550. meshLoaded(_this._defaultModel);
  61551. }
  61552. });
  61553. };
  61554. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61555. console.log("Button id: " + buttonIdx + "state: ");
  61556. console.dir(state);
  61557. };
  61558. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61559. GenericController.MODEL_FILENAME = 'generic.babylon';
  61560. return GenericController;
  61561. }(BABYLON.WebVRController));
  61562. BABYLON.GenericController = GenericController;
  61563. })(BABYLON || (BABYLON = {}));
  61564. //# sourceMappingURL=babylon.genericController.js.map
  61565. var BABYLON;
  61566. (function (BABYLON) {
  61567. var LoadedMeshInfo = /** @class */ (function () {
  61568. function LoadedMeshInfo() {
  61569. this.buttonMeshes = {};
  61570. this.axisMeshes = {};
  61571. }
  61572. return LoadedMeshInfo;
  61573. }());
  61574. var WindowsMotionController = /** @class */ (function (_super) {
  61575. __extends(WindowsMotionController, _super);
  61576. function WindowsMotionController(vrGamepad) {
  61577. var _this = _super.call(this, vrGamepad) || this;
  61578. _this._mapping = {
  61579. // Semantic button names
  61580. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  61581. // A mapping of the button name to glTF model node name
  61582. // that should be transformed by button value.
  61583. buttonMeshNames: {
  61584. 'trigger': 'SELECT',
  61585. 'menu': 'MENU',
  61586. 'grip': 'GRASP',
  61587. 'thumbstick': 'THUMBSTICK_PRESS',
  61588. 'trackpad': 'TOUCHPAD_PRESS'
  61589. },
  61590. // This mapping is used to translate from the Motion Controller to Babylon semantics
  61591. buttonObservableNames: {
  61592. 'trigger': 'onTriggerStateChangedObservable',
  61593. 'menu': 'onSecondaryButtonStateChangedObservable',
  61594. 'grip': 'onMainButtonStateChangedObservable',
  61595. 'thumbstick': 'onPadStateChangedObservable',
  61596. 'trackpad': 'onTrackpadChangedObservable'
  61597. },
  61598. // A mapping of the axis name to glTF model node name
  61599. // that should be transformed by axis value.
  61600. // This array mirrors the browserGamepad.axes array, such that
  61601. // the mesh corresponding to axis 0 is in this array index 0.
  61602. axisMeshNames: [
  61603. 'THUMBSTICK_X',
  61604. 'THUMBSTICK_Y',
  61605. 'TOUCHPAD_TOUCH_X',
  61606. 'TOUCHPAD_TOUCH_Y'
  61607. ],
  61608. pointingPoseMeshName: 'POINTING_POSE'
  61609. };
  61610. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  61611. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  61612. _this.trackpad = { x: 0, y: 0 };
  61613. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  61614. _this._loadedMeshInfo = null;
  61615. return _this;
  61616. }
  61617. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  61618. get: function () {
  61619. return this.onTriggerStateChangedObservable;
  61620. },
  61621. enumerable: true,
  61622. configurable: true
  61623. });
  61624. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  61625. get: function () {
  61626. return this.onSecondaryButtonStateChangedObservable;
  61627. },
  61628. enumerable: true,
  61629. configurable: true
  61630. });
  61631. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  61632. get: function () {
  61633. return this.onMainButtonStateChangedObservable;
  61634. },
  61635. enumerable: true,
  61636. configurable: true
  61637. });
  61638. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  61639. get: function () {
  61640. return this.onPadStateChangedObservable;
  61641. },
  61642. enumerable: true,
  61643. configurable: true
  61644. });
  61645. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  61646. get: function () {
  61647. return this.onTrackpadChangedObservable;
  61648. },
  61649. enumerable: true,
  61650. configurable: true
  61651. });
  61652. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  61653. get: function () {
  61654. return this.onTrackpadValuesChangedObservable;
  61655. },
  61656. enumerable: true,
  61657. configurable: true
  61658. });
  61659. /**
  61660. * Called once per frame by the engine.
  61661. */
  61662. WindowsMotionController.prototype.update = function () {
  61663. _super.prototype.update.call(this);
  61664. // Only need to animate axes if there is a loaded mesh
  61665. if (this._loadedMeshInfo) {
  61666. if (this.browserGamepad.axes) {
  61667. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  61668. this.trackpad.x = this.browserGamepad["axes"][2];
  61669. this.trackpad.y = this.browserGamepad["axes"][3];
  61670. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  61671. }
  61672. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  61673. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  61674. }
  61675. }
  61676. }
  61677. };
  61678. /**
  61679. * Called once for each button that changed state since the last frame
  61680. * @param buttonIdx Which button index changed
  61681. * @param state New state of the button
  61682. * @param changes Which properties on the state changed since last frame
  61683. */
  61684. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61685. var buttonName = this._mapping.buttons[buttonIdx];
  61686. if (!buttonName) {
  61687. return;
  61688. }
  61689. // Only emit events for buttons that we know how to map from index to name
  61690. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  61691. if (observable) {
  61692. observable.notifyObservers(state);
  61693. }
  61694. this.lerpButtonTransform(buttonName, state.value);
  61695. };
  61696. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  61697. // If there is no loaded mesh, there is nothing to transform.
  61698. if (!this._loadedMeshInfo) {
  61699. return;
  61700. }
  61701. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  61702. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61703. return;
  61704. }
  61705. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  61706. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  61707. };
  61708. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  61709. if (!this._loadedMeshInfo) {
  61710. return;
  61711. }
  61712. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  61713. if (!meshInfo) {
  61714. return;
  61715. }
  61716. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61717. return;
  61718. }
  61719. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  61720. var lerpValue = axisValue * 0.5 + 0.5;
  61721. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  61722. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  61723. };
  61724. /**
  61725. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  61726. * @param scene scene in which to add meshes
  61727. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  61728. */
  61729. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  61730. var _this = this;
  61731. if (forceDefault === void 0) { forceDefault = false; }
  61732. var path;
  61733. var filename;
  61734. // Checking if GLB loader is present
  61735. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  61736. // Determine the device specific folder based on the ID suffix
  61737. var device = 'default';
  61738. if (this.id && !forceDefault) {
  61739. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  61740. device = ((match && match[0]) || device);
  61741. }
  61742. // Hand
  61743. if (this.hand === 'left') {
  61744. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  61745. }
  61746. else {
  61747. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  61748. }
  61749. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  61750. }
  61751. else {
  61752. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  61753. path = BABYLON.GenericController.MODEL_BASE_URL;
  61754. filename = BABYLON.GenericController.MODEL_FILENAME;
  61755. }
  61756. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  61757. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  61758. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  61759. if (!_this._loadedMeshInfo) {
  61760. return;
  61761. }
  61762. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  61763. _this.attachToMesh(_this._defaultModel);
  61764. if (meshLoaded) {
  61765. meshLoaded(_this._defaultModel);
  61766. }
  61767. }, null, function (scene, message) {
  61768. BABYLON.Tools.Log(message);
  61769. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  61770. if (!forceDefault) {
  61771. _this.initControllerMesh(scene, meshLoaded, true);
  61772. }
  61773. });
  61774. };
  61775. /**
  61776. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  61777. * can be transformed by button presses and axes values, based on this._mapping.
  61778. *
  61779. * @param scene scene in which the meshes exist
  61780. * @param meshes list of meshes that make up the controller model to process
  61781. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  61782. */
  61783. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  61784. var loadedMeshInfo = null;
  61785. // Create a new mesh to contain the glTF hierarchy
  61786. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  61787. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  61788. var childMesh = null;
  61789. for (var i = 0; i < meshes.length; i++) {
  61790. var mesh = meshes[i];
  61791. if (!mesh.parent) {
  61792. // Exclude controller meshes from picking results
  61793. mesh.isPickable = false;
  61794. // Handle root node, attach to the new parentMesh
  61795. childMesh = mesh;
  61796. break;
  61797. }
  61798. }
  61799. if (childMesh) {
  61800. childMesh.setParent(parentMesh);
  61801. // Create our mesh info. Note that this method will always return non-null.
  61802. loadedMeshInfo = this.createMeshInfo(parentMesh);
  61803. }
  61804. else {
  61805. BABYLON.Tools.Warn('Could not find root node in model file.');
  61806. }
  61807. return loadedMeshInfo;
  61808. };
  61809. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  61810. var loadedMeshInfo = new LoadedMeshInfo();
  61811. var i;
  61812. loadedMeshInfo.rootNode = rootNode;
  61813. // Reset the caches
  61814. loadedMeshInfo.buttonMeshes = {};
  61815. loadedMeshInfo.axisMeshes = {};
  61816. // Button Meshes
  61817. for (i = 0; i < this._mapping.buttons.length; i++) {
  61818. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  61819. if (!buttonMeshName) {
  61820. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  61821. continue;
  61822. }
  61823. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  61824. if (!buttonMesh) {
  61825. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  61826. continue;
  61827. }
  61828. var buttonMeshInfo = {
  61829. index: i,
  61830. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  61831. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  61832. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  61833. };
  61834. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  61835. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  61836. }
  61837. else {
  61838. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  61839. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  61840. '(VALUE: ' + !!buttonMeshInfo.value +
  61841. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  61842. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  61843. ')');
  61844. }
  61845. }
  61846. // Axis Meshes
  61847. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  61848. var axisMeshName = this._mapping.axisMeshNames[i];
  61849. if (!axisMeshName) {
  61850. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  61851. continue;
  61852. }
  61853. var axisMesh = getChildByName(rootNode, axisMeshName);
  61854. if (!axisMesh) {
  61855. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  61856. continue;
  61857. }
  61858. var axisMeshInfo = {
  61859. index: i,
  61860. value: getImmediateChildByName(axisMesh, 'VALUE'),
  61861. min: getImmediateChildByName(axisMesh, 'MIN'),
  61862. max: getImmediateChildByName(axisMesh, 'MAX')
  61863. };
  61864. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  61865. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  61866. }
  61867. else {
  61868. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  61869. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  61870. '(VALUE: ' + !!axisMeshInfo.value +
  61871. ', MIN: ' + !!axisMeshInfo.min +
  61872. ', MAX:' + !!axisMeshInfo.max +
  61873. ')');
  61874. }
  61875. }
  61876. // Pointing Ray
  61877. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  61878. if (!loadedMeshInfo.pointingPoseNode) {
  61879. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  61880. }
  61881. return loadedMeshInfo;
  61882. // Look through all children recursively. This will return null if no mesh exists with the given name.
  61883. function getChildByName(node, name) {
  61884. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  61885. }
  61886. // Look through only immediate children. This will return null if no mesh exists with the given name.
  61887. function getImmediateChildByName(node, name) {
  61888. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  61889. }
  61890. };
  61891. WindowsMotionController.prototype.getForwardRay = function (length) {
  61892. if (length === void 0) { length = 100; }
  61893. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  61894. return _super.prototype.getForwardRay.call(this, length);
  61895. }
  61896. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  61897. var origin = m.getTranslation();
  61898. var forward = new BABYLON.Vector3(0, 0, -1);
  61899. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61900. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61901. return new BABYLON.Ray(origin, direction, length);
  61902. };
  61903. WindowsMotionController.prototype.dispose = function () {
  61904. _super.prototype.dispose.call(this);
  61905. this.onTrackpadChangedObservable.clear();
  61906. };
  61907. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  61908. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  61909. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  61910. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  61911. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  61912. return WindowsMotionController;
  61913. }(BABYLON.WebVRController));
  61914. BABYLON.WindowsMotionController = WindowsMotionController;
  61915. })(BABYLON || (BABYLON = {}));
  61916. //# sourceMappingURL=babylon.windowsMotionController.js.map
  61917. var BABYLON;
  61918. (function (BABYLON) {
  61919. var GearVRController = /** @class */ (function (_super) {
  61920. __extends(GearVRController, _super);
  61921. function GearVRController(vrGamepad) {
  61922. var _this = _super.call(this, vrGamepad) || this;
  61923. _this._buttonIndexToObservableNameMap = [
  61924. 'onTrackpadChangedObservable',
  61925. 'onTriggerStateChangedObservable' // Trigger
  61926. ];
  61927. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  61928. return _this;
  61929. }
  61930. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61931. var _this = this;
  61932. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  61933. _this._defaultModel = newMeshes[1];
  61934. _this.attachToMesh(_this._defaultModel);
  61935. if (meshLoaded) {
  61936. meshLoaded(_this._defaultModel);
  61937. }
  61938. });
  61939. };
  61940. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61941. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  61942. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  61943. // Only emit events for buttons that we know how to map from index to observable
  61944. var observable = this[observableName];
  61945. if (observable) {
  61946. observable.notifyObservers(state);
  61947. }
  61948. }
  61949. };
  61950. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61951. GearVRController.MODEL_FILENAME = 'generic.babylon';
  61952. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  61953. return GearVRController;
  61954. }(BABYLON.WebVRController));
  61955. BABYLON.GearVRController = GearVRController;
  61956. })(BABYLON || (BABYLON = {}));
  61957. //# sourceMappingURL=babylon.gearVRController.js.map
  61958. var BABYLON;
  61959. (function (BABYLON) {
  61960. var FollowCamera = /** @class */ (function (_super) {
  61961. __extends(FollowCamera, _super);
  61962. function FollowCamera(name, position, scene, lockedTarget) {
  61963. if (lockedTarget === void 0) { lockedTarget = null; }
  61964. var _this = _super.call(this, name, position, scene) || this;
  61965. _this.radius = 12;
  61966. _this.rotationOffset = 0;
  61967. _this.heightOffset = 4;
  61968. _this.cameraAcceleration = 0.05;
  61969. _this.maxCameraSpeed = 20;
  61970. _this.lockedTarget = lockedTarget;
  61971. return _this;
  61972. }
  61973. FollowCamera.prototype.getRadians = function (degrees) {
  61974. return degrees * Math.PI / 180;
  61975. };
  61976. FollowCamera.prototype.follow = function (cameraTarget) {
  61977. if (!cameraTarget)
  61978. return;
  61979. var yRotation;
  61980. if (cameraTarget.rotationQuaternion) {
  61981. var rotMatrix = new BABYLON.Matrix();
  61982. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  61983. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  61984. }
  61985. else {
  61986. yRotation = cameraTarget.rotation.y;
  61987. }
  61988. var radians = this.getRadians(this.rotationOffset) + yRotation;
  61989. var targetPosition = cameraTarget.getAbsolutePosition();
  61990. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  61991. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  61992. var dx = targetX - this.position.x;
  61993. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  61994. var dz = (targetZ) - this.position.z;
  61995. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  61996. var vy = dy * this.cameraAcceleration;
  61997. var vz = dz * this.cameraAcceleration * 2;
  61998. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  61999. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62000. }
  62001. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  62002. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62003. }
  62004. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  62005. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  62006. }
  62007. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  62008. this.setTarget(targetPosition);
  62009. };
  62010. FollowCamera.prototype._checkInputs = function () {
  62011. _super.prototype._checkInputs.call(this);
  62012. if (this.lockedTarget) {
  62013. this.follow(this.lockedTarget);
  62014. }
  62015. };
  62016. FollowCamera.prototype.getClassName = function () {
  62017. return "FollowCamera";
  62018. };
  62019. __decorate([
  62020. BABYLON.serialize()
  62021. ], FollowCamera.prototype, "radius", void 0);
  62022. __decorate([
  62023. BABYLON.serialize()
  62024. ], FollowCamera.prototype, "rotationOffset", void 0);
  62025. __decorate([
  62026. BABYLON.serialize()
  62027. ], FollowCamera.prototype, "heightOffset", void 0);
  62028. __decorate([
  62029. BABYLON.serialize()
  62030. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  62031. __decorate([
  62032. BABYLON.serialize()
  62033. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  62034. __decorate([
  62035. BABYLON.serializeAsMeshReference("lockedTargetId")
  62036. ], FollowCamera.prototype, "lockedTarget", void 0);
  62037. return FollowCamera;
  62038. }(BABYLON.TargetCamera));
  62039. BABYLON.FollowCamera = FollowCamera;
  62040. var ArcFollowCamera = /** @class */ (function (_super) {
  62041. __extends(ArcFollowCamera, _super);
  62042. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  62043. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  62044. _this.alpha = alpha;
  62045. _this.beta = beta;
  62046. _this.radius = radius;
  62047. _this.target = target;
  62048. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  62049. _this.follow();
  62050. return _this;
  62051. }
  62052. ArcFollowCamera.prototype.follow = function () {
  62053. if (!this.target) {
  62054. return;
  62055. }
  62056. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  62057. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  62058. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  62059. var targetPosition = this.target.getAbsolutePosition();
  62060. this.position = targetPosition.add(this._cartesianCoordinates);
  62061. this.setTarget(targetPosition);
  62062. };
  62063. ArcFollowCamera.prototype._checkInputs = function () {
  62064. _super.prototype._checkInputs.call(this);
  62065. this.follow();
  62066. };
  62067. ArcFollowCamera.prototype.getClassName = function () {
  62068. return "ArcFollowCamera";
  62069. };
  62070. return ArcFollowCamera;
  62071. }(BABYLON.TargetCamera));
  62072. BABYLON.ArcFollowCamera = ArcFollowCamera;
  62073. })(BABYLON || (BABYLON = {}));
  62074. //# sourceMappingURL=babylon.followCamera.js.map
  62075. var BABYLON;
  62076. (function (BABYLON) {
  62077. // We're mainly based on the logic defined into the FreeCamera code
  62078. var UniversalCamera = /** @class */ (function (_super) {
  62079. __extends(UniversalCamera, _super);
  62080. //-- end properties for backward compatibility for inputs
  62081. function UniversalCamera(name, position, scene) {
  62082. var _this = _super.call(this, name, position, scene) || this;
  62083. _this.inputs.addGamepad();
  62084. return _this;
  62085. }
  62086. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  62087. //-- Begin properties for backward compatibility for inputs
  62088. get: function () {
  62089. var gamepad = this.inputs.attached["gamepad"];
  62090. if (gamepad)
  62091. return gamepad.gamepadAngularSensibility;
  62092. return 0;
  62093. },
  62094. set: function (value) {
  62095. var gamepad = this.inputs.attached["gamepad"];
  62096. if (gamepad)
  62097. gamepad.gamepadAngularSensibility = value;
  62098. },
  62099. enumerable: true,
  62100. configurable: true
  62101. });
  62102. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  62103. get: function () {
  62104. var gamepad = this.inputs.attached["gamepad"];
  62105. if (gamepad)
  62106. return gamepad.gamepadMoveSensibility;
  62107. return 0;
  62108. },
  62109. set: function (value) {
  62110. var gamepad = this.inputs.attached["gamepad"];
  62111. if (gamepad)
  62112. gamepad.gamepadMoveSensibility = value;
  62113. },
  62114. enumerable: true,
  62115. configurable: true
  62116. });
  62117. UniversalCamera.prototype.getClassName = function () {
  62118. return "UniversalCamera";
  62119. };
  62120. return UniversalCamera;
  62121. }(BABYLON.TouchCamera));
  62122. BABYLON.UniversalCamera = UniversalCamera;
  62123. })(BABYLON || (BABYLON = {}));
  62124. //# sourceMappingURL=babylon.universalCamera.js.map
  62125. var BABYLON;
  62126. (function (BABYLON) {
  62127. // We're mainly based on the logic defined into the FreeCamera code
  62128. var GamepadCamera = /** @class */ (function (_super) {
  62129. __extends(GamepadCamera, _super);
  62130. //-- end properties for backward compatibility for inputs
  62131. function GamepadCamera(name, position, scene) {
  62132. return _super.call(this, name, position, scene) || this;
  62133. }
  62134. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  62135. //-- Begin properties for backward compatibility for inputs
  62136. get: function () {
  62137. var gamepad = this.inputs.attached["gamepad"];
  62138. if (gamepad)
  62139. return gamepad.gamepadAngularSensibility;
  62140. return 0;
  62141. },
  62142. set: function (value) {
  62143. var gamepad = this.inputs.attached["gamepad"];
  62144. if (gamepad)
  62145. gamepad.gamepadAngularSensibility = value;
  62146. },
  62147. enumerable: true,
  62148. configurable: true
  62149. });
  62150. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  62151. get: function () {
  62152. var gamepad = this.inputs.attached["gamepad"];
  62153. if (gamepad)
  62154. return gamepad.gamepadMoveSensibility;
  62155. return 0;
  62156. },
  62157. set: function (value) {
  62158. var gamepad = this.inputs.attached["gamepad"];
  62159. if (gamepad)
  62160. gamepad.gamepadMoveSensibility = value;
  62161. },
  62162. enumerable: true,
  62163. configurable: true
  62164. });
  62165. GamepadCamera.prototype.getClassName = function () {
  62166. return "GamepadCamera";
  62167. };
  62168. return GamepadCamera;
  62169. }(BABYLON.UniversalCamera));
  62170. BABYLON.GamepadCamera = GamepadCamera;
  62171. })(BABYLON || (BABYLON = {}));
  62172. //# sourceMappingURL=babylon.gamepadCamera.js.map
  62173. var BABYLON;
  62174. (function (BABYLON) {
  62175. var PostProcessRenderPipelineManager = /** @class */ (function () {
  62176. function PostProcessRenderPipelineManager() {
  62177. this._renderPipelines = {};
  62178. }
  62179. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  62180. this._renderPipelines[renderPipeline._name] = renderPipeline;
  62181. };
  62182. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  62183. if (unique === void 0) { unique = false; }
  62184. var renderPipeline = this._renderPipelines[renderPipelineName];
  62185. if (!renderPipeline) {
  62186. return;
  62187. }
  62188. renderPipeline._attachCameras(cameras, unique);
  62189. };
  62190. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  62191. var renderPipeline = this._renderPipelines[renderPipelineName];
  62192. if (!renderPipeline) {
  62193. return;
  62194. }
  62195. renderPipeline._detachCameras(cameras);
  62196. };
  62197. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62198. var renderPipeline = this._renderPipelines[renderPipelineName];
  62199. if (!renderPipeline) {
  62200. return;
  62201. }
  62202. renderPipeline._enableEffect(renderEffectName, cameras);
  62203. };
  62204. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  62205. var renderPipeline = this._renderPipelines[renderPipelineName];
  62206. if (!renderPipeline) {
  62207. return;
  62208. }
  62209. renderPipeline._disableEffect(renderEffectName, cameras);
  62210. };
  62211. PostProcessRenderPipelineManager.prototype.update = function () {
  62212. for (var renderPipelineName in this._renderPipelines) {
  62213. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62214. var pipeline = this._renderPipelines[renderPipelineName];
  62215. if (!pipeline.isSupported) {
  62216. pipeline.dispose();
  62217. delete this._renderPipelines[renderPipelineName];
  62218. }
  62219. else {
  62220. pipeline._update();
  62221. }
  62222. }
  62223. }
  62224. };
  62225. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  62226. for (var renderPipelineName in this._renderPipelines) {
  62227. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62228. var pipeline = this._renderPipelines[renderPipelineName];
  62229. pipeline._rebuild();
  62230. }
  62231. }
  62232. };
  62233. PostProcessRenderPipelineManager.prototype.dispose = function () {
  62234. for (var renderPipelineName in this._renderPipelines) {
  62235. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  62236. var pipeline = this._renderPipelines[renderPipelineName];
  62237. pipeline.dispose();
  62238. }
  62239. }
  62240. };
  62241. return PostProcessRenderPipelineManager;
  62242. }());
  62243. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  62244. })(BABYLON || (BABYLON = {}));
  62245. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  62246. var BABYLON;
  62247. (function (BABYLON) {
  62248. /**
  62249. * This represents a set of one or more post processes in Babylon.
  62250. * A post process can be used to apply a shader to a texture after it is rendered.
  62251. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  62252. */
  62253. var PostProcessRenderEffect = /** @class */ (function () {
  62254. /**
  62255. * Instantiates a post process render effect.
  62256. * A post process can be used to apply a shader to a texture after it is rendered.
  62257. * @param engine The engine the effect is tied to
  62258. * @param name The name of the effect
  62259. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  62260. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  62261. */
  62262. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  62263. this._name = name;
  62264. this._singleInstance = singleInstance || true;
  62265. this._getPostProcesses = getPostProcesses;
  62266. this._cameras = {};
  62267. this._indicesForCamera = {};
  62268. this._postProcesses = {};
  62269. }
  62270. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  62271. /**
  62272. * Checks if all the post processes in the effect are supported.
  62273. */
  62274. get: function () {
  62275. for (var index in this._postProcesses) {
  62276. for (var ppIndex in this._postProcesses[index]) {
  62277. if (!this._postProcesses[index][ppIndex].isSupported) {
  62278. return false;
  62279. }
  62280. }
  62281. }
  62282. return true;
  62283. },
  62284. enumerable: true,
  62285. configurable: true
  62286. });
  62287. /**
  62288. * Updates the current state of the effect
  62289. */
  62290. PostProcessRenderEffect.prototype._update = function () {
  62291. };
  62292. /**
  62293. * Attaches the effect on cameras
  62294. * @param cameras The camera to attach to.
  62295. */
  62296. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  62297. var _this = this;
  62298. var cameraKey;
  62299. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62300. if (!cams) {
  62301. return;
  62302. }
  62303. for (var i = 0; i < cams.length; i++) {
  62304. var camera = cams[i];
  62305. var cameraName = camera.name;
  62306. if (this._singleInstance) {
  62307. cameraKey = 0;
  62308. }
  62309. else {
  62310. cameraKey = cameraName;
  62311. }
  62312. if (!this._postProcesses[cameraKey]) {
  62313. var postProcess = this._getPostProcesses();
  62314. if (postProcess) {
  62315. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  62316. }
  62317. }
  62318. if (!this._indicesForCamera[cameraName]) {
  62319. this._indicesForCamera[cameraName] = [];
  62320. }
  62321. this._postProcesses[cameraKey].forEach(function (postProcess) {
  62322. var index = camera.attachPostProcess(postProcess);
  62323. _this._indicesForCamera[cameraName].push(index);
  62324. });
  62325. if (!this._cameras[cameraName]) {
  62326. this._cameras[cameraName] = camera;
  62327. }
  62328. }
  62329. };
  62330. /**
  62331. * Detatches the effect on cameras
  62332. * @param cameras The camera to detatch from.
  62333. */
  62334. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  62335. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62336. if (!cams) {
  62337. return;
  62338. }
  62339. for (var i = 0; i < cams.length; i++) {
  62340. var camera = cams[i];
  62341. var cameraName = camera.name;
  62342. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  62343. camera.detachPostProcess(postProcess);
  62344. });
  62345. if (this._cameras[cameraName]) {
  62346. //this._indicesForCamera.splice(index, 1);
  62347. this._cameras[cameraName] = null;
  62348. }
  62349. }
  62350. };
  62351. /**
  62352. * Enables the effect on given cameras
  62353. * @param cameras The camera to enable.
  62354. */
  62355. PostProcessRenderEffect.prototype._enable = function (cameras) {
  62356. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62357. if (!cams) {
  62358. return;
  62359. }
  62360. for (var i = 0; i < cams.length; i++) {
  62361. var camera = cams[i];
  62362. var cameraName = camera.name;
  62363. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  62364. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  62365. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  62366. }
  62367. }
  62368. }
  62369. };
  62370. /**
  62371. * Disables the effect on the given cameras
  62372. * @param cameras The camera to disable.
  62373. */
  62374. PostProcessRenderEffect.prototype._disable = function (cameras) {
  62375. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62376. if (!cams) {
  62377. return;
  62378. }
  62379. for (var i = 0; i < cams.length; i++) {
  62380. var camera = cams[i];
  62381. var cameraName = camera.Name;
  62382. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  62383. }
  62384. };
  62385. /**
  62386. * Gets a list of the post processes contained in the effect.
  62387. * @param camera The camera to get the post processes on.
  62388. * @returns The list of the post processes in the effect.
  62389. */
  62390. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  62391. if (this._singleInstance) {
  62392. return this._postProcesses[0];
  62393. }
  62394. else {
  62395. if (!camera) {
  62396. return null;
  62397. }
  62398. return this._postProcesses[camera.name];
  62399. }
  62400. };
  62401. return PostProcessRenderEffect;
  62402. }());
  62403. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  62404. })(BABYLON || (BABYLON = {}));
  62405. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  62406. var BABYLON;
  62407. (function (BABYLON) {
  62408. var PostProcessRenderPipeline = /** @class */ (function () {
  62409. function PostProcessRenderPipeline(engine, name) {
  62410. this._name = name;
  62411. this._renderEffects = {};
  62412. this._renderEffectsForIsolatedPass = new Array();
  62413. this._cameras = [];
  62414. }
  62415. PostProcessRenderPipeline.prototype.getClassName = function () {
  62416. return "PostProcessRenderPipeline";
  62417. };
  62418. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  62419. get: function () {
  62420. for (var renderEffectName in this._renderEffects) {
  62421. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62422. if (!this._renderEffects[renderEffectName].isSupported) {
  62423. return false;
  62424. }
  62425. }
  62426. }
  62427. return true;
  62428. },
  62429. enumerable: true,
  62430. configurable: true
  62431. });
  62432. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  62433. this._renderEffects[renderEffect._name] = renderEffect;
  62434. };
  62435. // private
  62436. PostProcessRenderPipeline.prototype._rebuild = function () {
  62437. };
  62438. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  62439. var renderEffects = this._renderEffects[renderEffectName];
  62440. if (!renderEffects) {
  62441. return;
  62442. }
  62443. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62444. };
  62445. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  62446. var renderEffects = this._renderEffects[renderEffectName];
  62447. if (!renderEffects) {
  62448. return;
  62449. }
  62450. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62451. };
  62452. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  62453. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62454. if (!cams) {
  62455. return;
  62456. }
  62457. var indicesToDelete = [];
  62458. var i;
  62459. for (i = 0; i < cams.length; i++) {
  62460. var camera = cams[i];
  62461. var cameraName = camera.name;
  62462. if (this._cameras.indexOf(camera) === -1) {
  62463. this._cameras[cameraName] = camera;
  62464. }
  62465. else if (unique) {
  62466. indicesToDelete.push(i);
  62467. }
  62468. }
  62469. for (i = 0; i < indicesToDelete.length; i++) {
  62470. cameras.splice(indicesToDelete[i], 1);
  62471. }
  62472. for (var renderEffectName in this._renderEffects) {
  62473. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62474. this._renderEffects[renderEffectName]._attachCameras(cams);
  62475. }
  62476. }
  62477. };
  62478. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  62479. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62480. if (!cams) {
  62481. return;
  62482. }
  62483. for (var renderEffectName in this._renderEffects) {
  62484. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62485. this._renderEffects[renderEffectName]._detachCameras(cams);
  62486. }
  62487. }
  62488. for (var i = 0; i < cams.length; i++) {
  62489. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  62490. }
  62491. };
  62492. PostProcessRenderPipeline.prototype._update = function () {
  62493. for (var renderEffectName in this._renderEffects) {
  62494. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62495. this._renderEffects[renderEffectName]._update();
  62496. }
  62497. }
  62498. for (var i = 0; i < this._cameras.length; i++) {
  62499. var cameraName = this._cameras[i].name;
  62500. if (this._renderEffectsForIsolatedPass[cameraName]) {
  62501. this._renderEffectsForIsolatedPass[cameraName]._update();
  62502. }
  62503. }
  62504. };
  62505. PostProcessRenderPipeline.prototype._reset = function () {
  62506. this._renderEffects = {};
  62507. this._renderEffectsForIsolatedPass = new Array();
  62508. };
  62509. PostProcessRenderPipeline.prototype.dispose = function () {
  62510. // Must be implemented by children
  62511. };
  62512. __decorate([
  62513. BABYLON.serialize()
  62514. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  62515. return PostProcessRenderPipeline;
  62516. }());
  62517. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  62518. })(BABYLON || (BABYLON = {}));
  62519. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  62520. var BABYLON;
  62521. (function (BABYLON) {
  62522. var DepthRenderer = /** @class */ (function () {
  62523. function DepthRenderer(scene, type) {
  62524. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  62525. var _this = this;
  62526. this._scene = scene;
  62527. var engine = scene.getEngine();
  62528. // Render target
  62529. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  62530. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62531. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62532. this._depthMap.refreshRate = 1;
  62533. this._depthMap.renderParticles = false;
  62534. this._depthMap.renderList = null;
  62535. // set default depth value to 1.0 (far away)
  62536. this._depthMap.onClearObservable.add(function (engine) {
  62537. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  62538. });
  62539. // Custom render function
  62540. var renderSubMesh = function (subMesh) {
  62541. var mesh = subMesh.getRenderingMesh();
  62542. var scene = _this._scene;
  62543. var engine = scene.getEngine();
  62544. var material = subMesh.getMaterial();
  62545. if (!material) {
  62546. return;
  62547. }
  62548. // Culling and reverse (right handed system)
  62549. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  62550. // Managing instances
  62551. var batch = mesh._getInstancesRenderList(subMesh._id);
  62552. if (batch.mustReturn) {
  62553. return;
  62554. }
  62555. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62556. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  62557. engine.enableEffect(_this._effect);
  62558. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  62559. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  62560. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  62561. // Alpha test
  62562. if (material && material.needAlphaTesting()) {
  62563. var alphaTexture = material.getAlphaTestTexture();
  62564. if (alphaTexture) {
  62565. _this._effect.setTexture("diffuseSampler", alphaTexture);
  62566. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62567. }
  62568. }
  62569. // Bones
  62570. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62571. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62572. }
  62573. // Draw
  62574. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62575. }
  62576. };
  62577. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62578. var index;
  62579. if (depthOnlySubMeshes.length) {
  62580. engine.setColorWrite(false);
  62581. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62582. renderSubMesh(depthOnlySubMeshes.data[index]);
  62583. }
  62584. engine.setColorWrite(true);
  62585. }
  62586. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62587. renderSubMesh(opaqueSubMeshes.data[index]);
  62588. }
  62589. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62590. renderSubMesh(alphaTestSubMeshes.data[index]);
  62591. }
  62592. };
  62593. }
  62594. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  62595. var material = subMesh.getMaterial();
  62596. if (material.disableDepthWrite) {
  62597. return false;
  62598. }
  62599. var defines = [];
  62600. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62601. var mesh = subMesh.getMesh();
  62602. // Alpha test
  62603. if (material && material.needAlphaTesting()) {
  62604. defines.push("#define ALPHATEST");
  62605. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62606. attribs.push(BABYLON.VertexBuffer.UVKind);
  62607. defines.push("#define UV1");
  62608. }
  62609. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62610. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62611. defines.push("#define UV2");
  62612. }
  62613. }
  62614. // Bones
  62615. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62616. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62617. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62618. if (mesh.numBoneInfluencers > 4) {
  62619. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62620. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62621. }
  62622. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62623. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62624. }
  62625. else {
  62626. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62627. }
  62628. // Instances
  62629. if (useInstances) {
  62630. defines.push("#define INSTANCES");
  62631. attribs.push("world0");
  62632. attribs.push("world1");
  62633. attribs.push("world2");
  62634. attribs.push("world3");
  62635. }
  62636. // Get correct effect
  62637. var join = defines.join("\n");
  62638. if (this._cachedDefines !== join) {
  62639. this._cachedDefines = join;
  62640. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  62641. }
  62642. return this._effect.isReady();
  62643. };
  62644. DepthRenderer.prototype.getDepthMap = function () {
  62645. return this._depthMap;
  62646. };
  62647. // Methods
  62648. DepthRenderer.prototype.dispose = function () {
  62649. this._depthMap.dispose();
  62650. };
  62651. return DepthRenderer;
  62652. }());
  62653. BABYLON.DepthRenderer = DepthRenderer;
  62654. })(BABYLON || (BABYLON = {}));
  62655. //# sourceMappingURL=babylon.depthRenderer.js.map
  62656. var BABYLON;
  62657. (function (BABYLON) {
  62658. var SSAORenderingPipeline = /** @class */ (function (_super) {
  62659. __extends(SSAORenderingPipeline, _super);
  62660. /**
  62661. * @constructor
  62662. * @param {string} name - The rendering pipeline name
  62663. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62664. * @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 }
  62665. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62666. */
  62667. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  62668. var _this = _super.call(this, scene.getEngine(), name) || this;
  62669. // Members
  62670. /**
  62671. * The PassPostProcess id in the pipeline that contains the original scene color
  62672. * @type {string}
  62673. */
  62674. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62675. /**
  62676. * The SSAO PostProcess id in the pipeline
  62677. * @type {string}
  62678. */
  62679. _this.SSAORenderEffect = "SSAORenderEffect";
  62680. /**
  62681. * The horizontal blur PostProcess id in the pipeline
  62682. * @type {string}
  62683. */
  62684. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62685. /**
  62686. * The vertical blur PostProcess id in the pipeline
  62687. * @type {string}
  62688. */
  62689. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62690. /**
  62691. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62692. * @type {string}
  62693. */
  62694. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62695. /**
  62696. * The output strength of the SSAO post-process. Default value is 1.0.
  62697. * @type {number}
  62698. */
  62699. _this.totalStrength = 1.0;
  62700. /**
  62701. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  62702. * @type {number}
  62703. */
  62704. _this.radius = 0.0001;
  62705. /**
  62706. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  62707. * Must not be equal to fallOff and superior to fallOff.
  62708. * Default value is 0.975
  62709. * @type {number}
  62710. */
  62711. _this.area = 0.0075;
  62712. /**
  62713. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  62714. * Must not be equal to area and inferior to area.
  62715. * Default value is 0.0
  62716. * @type {number}
  62717. */
  62718. _this.fallOff = 0.000001;
  62719. /**
  62720. * The base color of the SSAO post-process
  62721. * The final result is "base + ssao" between [0, 1]
  62722. * @type {number}
  62723. */
  62724. _this.base = 0.5;
  62725. _this._firstUpdate = true;
  62726. _this._scene = scene;
  62727. // Set up assets
  62728. _this._createRandomTexture();
  62729. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62730. var ssaoRatio = ratio.ssaoRatio || ratio;
  62731. var combineRatio = ratio.combineRatio || ratio;
  62732. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62733. _this._createSSAOPostProcess(ssaoRatio);
  62734. _this._createBlurPostProcess(ssaoRatio);
  62735. _this._createSSAOCombinePostProcess(combineRatio);
  62736. // Set up pipeline
  62737. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62738. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62739. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62740. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62741. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62742. // Finish
  62743. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62744. if (cameras)
  62745. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62746. return _this;
  62747. }
  62748. // Public Methods
  62749. /**
  62750. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62751. */
  62752. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62753. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62754. for (var i = 0; i < this._scene.cameras.length; i++) {
  62755. var camera = this._scene.cameras[i];
  62756. this._originalColorPostProcess.dispose(camera);
  62757. this._ssaoPostProcess.dispose(camera);
  62758. this._blurHPostProcess.dispose(camera);
  62759. this._blurVPostProcess.dispose(camera);
  62760. this._ssaoCombinePostProcess.dispose(camera);
  62761. }
  62762. this._randomTexture.dispose();
  62763. if (disableDepthRender)
  62764. this._scene.disableDepthRenderer();
  62765. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62766. _super.prototype.dispose.call(this);
  62767. };
  62768. // Private Methods
  62769. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  62770. var _this = this;
  62771. var size = 16;
  62772. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62773. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62774. this._blurHPostProcess.onActivateObservable.add(function () {
  62775. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  62776. _this._blurHPostProcess.kernel = size * dw;
  62777. });
  62778. this._blurVPostProcess.onActivateObservable.add(function () {
  62779. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  62780. _this._blurVPostProcess.kernel = size * dw;
  62781. });
  62782. };
  62783. SSAORenderingPipeline.prototype._rebuild = function () {
  62784. this._firstUpdate = true;
  62785. _super.prototype._rebuild.call(this);
  62786. };
  62787. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62788. var _this = this;
  62789. var numSamples = 16;
  62790. var sampleSphere = [
  62791. 0.5381, 0.1856, -0.4319,
  62792. 0.1379, 0.2486, 0.4430,
  62793. 0.3371, 0.5679, -0.0057,
  62794. -0.6999, -0.0451, -0.0019,
  62795. 0.0689, -0.1598, -0.8547,
  62796. 0.0560, 0.0069, -0.1843,
  62797. -0.0146, 0.1402, 0.0762,
  62798. 0.0100, -0.1924, -0.0344,
  62799. -0.3577, -0.5301, -0.4358,
  62800. -0.3169, 0.1063, 0.0158,
  62801. 0.0103, -0.5869, 0.0046,
  62802. -0.0897, -0.4940, 0.3287,
  62803. 0.7119, -0.0154, -0.0918,
  62804. -0.0533, 0.0596, -0.5411,
  62805. 0.0352, -0.0631, 0.5460,
  62806. -0.4776, 0.2847, -0.0271
  62807. ];
  62808. var samplesFactor = 1.0 / numSamples;
  62809. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  62810. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62811. "area", "fallOff", "base", "range", "viewport"
  62812. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62813. this._ssaoPostProcess.onApply = function (effect) {
  62814. if (_this._firstUpdate) {
  62815. effect.setArray3("sampleSphere", sampleSphere);
  62816. effect.setFloat("samplesFactor", samplesFactor);
  62817. effect.setFloat("randTextureTiles", 4.0);
  62818. }
  62819. effect.setFloat("totalStrength", _this.totalStrength);
  62820. effect.setFloat("radius", _this.radius);
  62821. effect.setFloat("area", _this.area);
  62822. effect.setFloat("fallOff", _this.fallOff);
  62823. effect.setFloat("base", _this.base);
  62824. effect.setTexture("textureSampler", _this._depthTexture);
  62825. effect.setTexture("randomSampler", _this._randomTexture);
  62826. };
  62827. };
  62828. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62829. var _this = this;
  62830. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62831. this._ssaoCombinePostProcess.onApply = function (effect) {
  62832. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62833. };
  62834. };
  62835. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  62836. var size = 512;
  62837. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62838. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62839. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62840. var context = this._randomTexture.getContext();
  62841. var rand = function (min, max) {
  62842. return Math.random() * (max - min) + min;
  62843. };
  62844. var randVector = BABYLON.Vector3.Zero();
  62845. for (var x = 0; x < size; x++) {
  62846. for (var y = 0; y < size; y++) {
  62847. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  62848. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  62849. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  62850. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62851. context.fillRect(x, y, 1, 1);
  62852. }
  62853. }
  62854. this._randomTexture.update(false);
  62855. };
  62856. __decorate([
  62857. BABYLON.serialize()
  62858. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  62859. __decorate([
  62860. BABYLON.serialize()
  62861. ], SSAORenderingPipeline.prototype, "radius", void 0);
  62862. __decorate([
  62863. BABYLON.serialize()
  62864. ], SSAORenderingPipeline.prototype, "area", void 0);
  62865. __decorate([
  62866. BABYLON.serialize()
  62867. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  62868. __decorate([
  62869. BABYLON.serialize()
  62870. ], SSAORenderingPipeline.prototype, "base", void 0);
  62871. return SSAORenderingPipeline;
  62872. }(BABYLON.PostProcessRenderPipeline));
  62873. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  62874. })(BABYLON || (BABYLON = {}));
  62875. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  62876. var BABYLON;
  62877. (function (BABYLON) {
  62878. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  62879. __extends(SSAO2RenderingPipeline, _super);
  62880. /**
  62881. * @constructor
  62882. * @param {string} name - The rendering pipeline name
  62883. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62884. * @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 }
  62885. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62886. */
  62887. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  62888. var _this = _super.call(this, scene.getEngine(), name) || this;
  62889. // Members
  62890. /**
  62891. * The PassPostProcess id in the pipeline that contains the original scene color
  62892. * @type {string}
  62893. */
  62894. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62895. /**
  62896. * The SSAO PostProcess id in the pipeline
  62897. * @type {string}
  62898. */
  62899. _this.SSAORenderEffect = "SSAORenderEffect";
  62900. /**
  62901. * The horizontal blur PostProcess id in the pipeline
  62902. * @type {string}
  62903. */
  62904. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62905. /**
  62906. * The vertical blur PostProcess id in the pipeline
  62907. * @type {string}
  62908. */
  62909. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62910. /**
  62911. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62912. * @type {string}
  62913. */
  62914. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62915. /**
  62916. * The output strength of the SSAO post-process. Default value is 1.0.
  62917. * @type {number}
  62918. */
  62919. _this.totalStrength = 1.0;
  62920. /**
  62921. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  62922. * @type {number}
  62923. */
  62924. _this.maxZ = 100.0;
  62925. /**
  62926. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  62927. * @type {number}
  62928. */
  62929. _this.minZAspect = 0.2;
  62930. /**
  62931. * Number of samples used for the SSAO calculations. Default value is 8
  62932. * @type {number}
  62933. */
  62934. _this._samples = 8;
  62935. /**
  62936. * Are we using bilateral blur ?
  62937. * @type {boolean}
  62938. */
  62939. _this._expensiveBlur = true;
  62940. /**
  62941. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  62942. * @type {number}
  62943. */
  62944. _this.radius = 2.0;
  62945. /**
  62946. * The base color of the SSAO post-process
  62947. * The final result is "base + ssao" between [0, 1]
  62948. * @type {number}
  62949. */
  62950. _this.base = 0.1;
  62951. _this._firstUpdate = true;
  62952. _this._scene = scene;
  62953. if (!_this.isSupported) {
  62954. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  62955. return _this;
  62956. }
  62957. var ssaoRatio = ratio.ssaoRatio || ratio;
  62958. var blurRatio = ratio.blurRatio || ratio;
  62959. // Set up assets
  62960. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  62961. _this._createRandomTexture();
  62962. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  62963. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  62964. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62965. _this._createSSAOPostProcess(1.0);
  62966. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  62967. _this._createSSAOCombinePostProcess(blurRatio);
  62968. // Set up pipeline
  62969. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62970. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62971. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62974. // Finish
  62975. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62976. if (cameras)
  62977. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62978. return _this;
  62979. }
  62980. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  62981. get: function () {
  62982. return this._samples;
  62983. },
  62984. set: function (n) {
  62985. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  62986. this._samples = n;
  62987. this._sampleSphere = this._generateHemisphere();
  62988. this._firstUpdate = true;
  62989. },
  62990. enumerable: true,
  62991. configurable: true
  62992. });
  62993. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  62994. get: function () {
  62995. return this._expensiveBlur;
  62996. },
  62997. set: function (b) {
  62998. 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"]);
  62999. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  63000. this._expensiveBlur = b;
  63001. this._firstUpdate = true;
  63002. },
  63003. enumerable: true,
  63004. configurable: true
  63005. });
  63006. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  63007. /**
  63008. * Support test.
  63009. * @type {boolean}
  63010. */
  63011. get: function () {
  63012. var engine = BABYLON.Engine.LastCreatedEngine;
  63013. if (!engine) {
  63014. return false;
  63015. }
  63016. return engine.getCaps().drawBuffersExtension;
  63017. },
  63018. enumerable: true,
  63019. configurable: true
  63020. });
  63021. // Public Methods
  63022. /**
  63023. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  63024. */
  63025. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  63026. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  63027. for (var i = 0; i < this._scene.cameras.length; i++) {
  63028. var camera = this._scene.cameras[i];
  63029. this._originalColorPostProcess.dispose(camera);
  63030. this._ssaoPostProcess.dispose(camera);
  63031. this._blurHPostProcess.dispose(camera);
  63032. this._blurVPostProcess.dispose(camera);
  63033. this._ssaoCombinePostProcess.dispose(camera);
  63034. }
  63035. this._randomTexture.dispose();
  63036. if (disableGeometryBufferRenderer)
  63037. this._scene.disableGeometryBufferRenderer();
  63038. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63039. _super.prototype.dispose.call(this);
  63040. };
  63041. // Private Methods
  63042. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  63043. var _this = this;
  63044. this._samplerOffsets = [];
  63045. var expensive = this.expensiveBlur;
  63046. for (var i = -8; i < 8; i++) {
  63047. this._samplerOffsets.push(i * 2 + 0.5);
  63048. }
  63049. 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");
  63050. this._blurHPostProcess.onApply = function (effect) {
  63051. if (!_this._scene.activeCamera) {
  63052. return;
  63053. }
  63054. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  63055. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63056. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63057. effect.setFloat("radius", _this.radius);
  63058. effect.setTexture("depthSampler", _this._depthTexture);
  63059. if (_this._firstUpdate) {
  63060. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63061. }
  63062. };
  63063. 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");
  63064. this._blurVPostProcess.onApply = function (effect) {
  63065. if (!_this._scene.activeCamera) {
  63066. return;
  63067. }
  63068. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  63069. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63070. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63071. effect.setFloat("radius", _this.radius);
  63072. effect.setTexture("depthSampler", _this._depthTexture);
  63073. if (_this._firstUpdate) {
  63074. effect.setArray("samplerOffsets", _this._samplerOffsets);
  63075. _this._firstUpdate = false;
  63076. }
  63077. };
  63078. };
  63079. SSAO2RenderingPipeline.prototype._rebuild = function () {
  63080. this._firstUpdate = true;
  63081. _super.prototype._rebuild.call(this);
  63082. };
  63083. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  63084. var numSamples = this.samples;
  63085. var result = [];
  63086. var vector, scale;
  63087. var rand = function (min, max) {
  63088. return Math.random() * (max - min) + min;
  63089. };
  63090. var i = 0;
  63091. while (i < numSamples) {
  63092. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  63093. vector.normalize();
  63094. scale = i / numSamples;
  63095. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  63096. vector.scaleInPlace(scale);
  63097. result.push(vector.x, vector.y, vector.z);
  63098. i++;
  63099. }
  63100. return result;
  63101. };
  63102. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  63103. var _this = this;
  63104. var numSamples = this.samples;
  63105. this._sampleSphere = this._generateHemisphere();
  63106. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  63107. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  63108. "base", "range", "projection", "near", "far", "texelSize",
  63109. "xViewport", "yViewport", "maxZ", "minZAspect"
  63110. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  63111. this._ssaoPostProcess.onApply = function (effect) {
  63112. if (_this._firstUpdate) {
  63113. effect.setArray3("sampleSphere", _this._sampleSphere);
  63114. effect.setFloat("randTextureTiles", 4.0);
  63115. }
  63116. if (!_this._scene.activeCamera) {
  63117. return;
  63118. }
  63119. effect.setFloat("samplesFactor", 1 / _this.samples);
  63120. effect.setFloat("totalStrength", _this.totalStrength);
  63121. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  63122. effect.setFloat("radius", _this.radius);
  63123. effect.setFloat("maxZ", _this.maxZ);
  63124. effect.setFloat("minZAspect", _this.minZAspect);
  63125. effect.setFloat("base", _this.base);
  63126. effect.setFloat("near", _this._scene.activeCamera.minZ);
  63127. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  63128. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  63129. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  63130. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  63131. effect.setTexture("textureSampler", _this._depthTexture);
  63132. effect.setTexture("normalSampler", _this._normalTexture);
  63133. effect.setTexture("randomSampler", _this._randomTexture);
  63134. };
  63135. };
  63136. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  63137. var _this = this;
  63138. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63139. this._ssaoCombinePostProcess.onApply = function (effect) {
  63140. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  63141. };
  63142. };
  63143. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  63144. var size = 512;
  63145. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63146. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63147. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63148. var context = this._randomTexture.getContext();
  63149. var rand = function (min, max) {
  63150. return Math.random() * (max - min) + min;
  63151. };
  63152. var randVector = BABYLON.Vector3.Zero();
  63153. for (var x = 0; x < size; x++) {
  63154. for (var y = 0; y < size; y++) {
  63155. randVector.x = rand(0.0, 1.0);
  63156. randVector.y = rand(0.0, 1.0);
  63157. randVector.z = 0.0;
  63158. randVector.normalize();
  63159. randVector.scaleInPlace(255);
  63160. randVector.x = Math.floor(randVector.x);
  63161. randVector.y = Math.floor(randVector.y);
  63162. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  63163. context.fillRect(x, y, 1, 1);
  63164. }
  63165. }
  63166. this._randomTexture.update(false);
  63167. };
  63168. __decorate([
  63169. BABYLON.serialize()
  63170. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  63171. __decorate([
  63172. BABYLON.serialize()
  63173. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  63174. __decorate([
  63175. BABYLON.serialize()
  63176. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  63177. __decorate([
  63178. BABYLON.serialize("samples")
  63179. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  63180. __decorate([
  63181. BABYLON.serialize("expensiveBlur")
  63182. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  63183. __decorate([
  63184. BABYLON.serialize()
  63185. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  63186. __decorate([
  63187. BABYLON.serialize()
  63188. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  63189. return SSAO2RenderingPipeline;
  63190. }(BABYLON.PostProcessRenderPipeline));
  63191. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  63192. })(BABYLON || (BABYLON = {}));
  63193. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  63194. // BABYLON.JS Chromatic Aberration GLSL Shader
  63195. // Author: Olivier Guyot
  63196. // Separates very slightly R, G and B colors on the edges of the screen
  63197. // Inspired by Francois Tarlier & Martins Upitis
  63198. var BABYLON;
  63199. (function (BABYLON) {
  63200. var LensRenderingPipeline = /** @class */ (function (_super) {
  63201. __extends(LensRenderingPipeline, _super);
  63202. /**
  63203. * @constructor
  63204. *
  63205. * Effect parameters are as follow:
  63206. * {
  63207. * chromatic_aberration: number; // from 0 to x (1 for realism)
  63208. * edge_blur: number; // from 0 to x (1 for realism)
  63209. * distortion: number; // from 0 to x (1 for realism)
  63210. * grain_amount: number; // from 0 to 1
  63211. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  63212. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  63213. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  63214. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  63215. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  63216. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  63217. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  63218. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  63219. * }
  63220. * Note: if an effect parameter is unset, effect is disabled
  63221. *
  63222. * @param {string} name - The rendering pipeline name
  63223. * @param {object} parameters - An object containing all parameters (see above)
  63224. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63225. * @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)
  63226. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63227. */
  63228. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  63229. if (ratio === void 0) { ratio = 1.0; }
  63230. var _this = _super.call(this, scene.getEngine(), name) || this;
  63231. // Lens effects can be of the following:
  63232. // - chromatic aberration (slight shift of RGB colors)
  63233. // - blur on the edge of the lens
  63234. // - lens distortion
  63235. // - depth-of-field blur & highlights enhancing
  63236. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  63237. // - grain effect (noise or custom texture)
  63238. // Two additional texture samplers are needed:
  63239. // - depth map (for depth-of-field)
  63240. // - grain texture
  63241. /**
  63242. * The chromatic aberration PostProcess id in the pipeline
  63243. * @type {string}
  63244. */
  63245. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  63246. /**
  63247. * The highlights enhancing PostProcess id in the pipeline
  63248. * @type {string}
  63249. */
  63250. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  63251. /**
  63252. * The depth-of-field PostProcess id in the pipeline
  63253. * @type {string}
  63254. */
  63255. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  63256. _this._scene = scene;
  63257. // Fetch texture samplers
  63258. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  63259. if (parameters.grain_texture) {
  63260. _this._grainTexture = parameters.grain_texture;
  63261. }
  63262. else {
  63263. _this._createGrainTexture();
  63264. }
  63265. // save parameters
  63266. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  63267. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  63268. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  63269. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  63270. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  63271. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  63272. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  63273. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  63274. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  63275. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  63276. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  63277. // Create effects
  63278. _this._createChromaticAberrationPostProcess(ratio);
  63279. _this._createHighlightsPostProcess(ratio);
  63280. _this._createDepthOfFieldPostProcess(ratio / 4);
  63281. // Set up pipeline
  63282. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  63283. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  63284. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  63285. if (_this._highlightsGain === -1) {
  63286. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  63287. }
  63288. // Finish
  63289. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63290. if (cameras) {
  63291. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  63292. }
  63293. return _this;
  63294. }
  63295. // public methods (self explanatory)
  63296. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  63297. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  63298. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  63299. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  63300. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  63301. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  63302. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  63303. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  63304. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  63305. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  63306. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  63307. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  63308. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  63309. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  63310. };
  63311. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  63312. this._highlightsPostProcess.updateEffect();
  63313. };
  63314. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  63315. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  63316. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  63317. this._highlightsGain = amount;
  63318. };
  63319. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  63320. if (this._highlightsGain === -1) {
  63321. this._highlightsGain = 1.0;
  63322. }
  63323. this._highlightsThreshold = amount;
  63324. };
  63325. LensRenderingPipeline.prototype.disableHighlights = function () {
  63326. this._highlightsGain = -1;
  63327. };
  63328. /**
  63329. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  63330. */
  63331. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  63332. if (disableDepthRender === void 0) { disableDepthRender = false; }
  63333. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  63334. this._chromaticAberrationPostProcess = null;
  63335. this._highlightsPostProcess = null;
  63336. this._depthOfFieldPostProcess = null;
  63337. this._grainTexture.dispose();
  63338. if (disableDepthRender)
  63339. this._scene.disableDepthRenderer();
  63340. };
  63341. // colors shifting and distortion
  63342. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  63343. var _this = this;
  63344. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  63345. [], // samplers
  63346. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63347. this._chromaticAberrationPostProcess.onApply = function (effect) {
  63348. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  63349. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63350. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63351. };
  63352. };
  63353. // highlights enhancing
  63354. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  63355. var _this = this;
  63356. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  63357. [], // samplers
  63358. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  63359. this._highlightsPostProcess.onApply = function (effect) {
  63360. effect.setFloat('gain', _this._highlightsGain);
  63361. effect.setFloat('threshold', _this._highlightsThreshold);
  63362. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  63363. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63364. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63365. };
  63366. };
  63367. // colors shifting and distortion
  63368. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  63369. var _this = this;
  63370. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  63371. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  63372. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  63373. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  63374. this._depthOfFieldPostProcess.onApply = function (effect) {
  63375. effect.setTexture("depthSampler", _this._depthTexture);
  63376. effect.setTexture("grainSampler", _this._grainTexture);
  63377. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  63378. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  63379. effect.setFloat('grain_amount', _this._grainAmount);
  63380. effect.setBool('blur_noise', _this._blurNoise);
  63381. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63382. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63383. effect.setFloat('distortion', _this._distortion);
  63384. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  63385. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  63386. effect.setFloat('aperture', _this._dofAperture);
  63387. effect.setFloat('darken', _this._dofDarken);
  63388. effect.setFloat('edge_blur', _this._edgeBlur);
  63389. effect.setBool('highlights', (_this._highlightsGain !== -1));
  63390. if (_this._scene.activeCamera) {
  63391. effect.setFloat('near', _this._scene.activeCamera.minZ);
  63392. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  63393. }
  63394. };
  63395. };
  63396. // creates a black and white random noise texture, 512x512
  63397. LensRenderingPipeline.prototype._createGrainTexture = function () {
  63398. var size = 512;
  63399. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63400. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63401. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63402. var context = this._grainTexture.getContext();
  63403. var rand = function (min, max) {
  63404. return Math.random() * (max - min) + min;
  63405. };
  63406. var value;
  63407. for (var x = 0; x < size; x++) {
  63408. for (var y = 0; y < size; y++) {
  63409. value = Math.floor(rand(0.42, 0.58) * 255);
  63410. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  63411. context.fillRect(x, y, 1, 1);
  63412. }
  63413. }
  63414. this._grainTexture.update(false);
  63415. };
  63416. return LensRenderingPipeline;
  63417. }(BABYLON.PostProcessRenderPipeline));
  63418. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  63419. })(BABYLON || (BABYLON = {}));
  63420. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  63421. var BABYLON;
  63422. (function (BABYLON) {
  63423. var StandardRenderingPipeline = /** @class */ (function (_super) {
  63424. __extends(StandardRenderingPipeline, _super);
  63425. /**
  63426. * @constructor
  63427. * @param {string} name - The rendering pipeline name
  63428. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63429. * @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)
  63430. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63431. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63432. */
  63433. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63434. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63435. var _this = _super.call(this, scene.getEngine(), name) || this;
  63436. _this.downSampleX4PostProcess = null;
  63437. _this.brightPassPostProcess = null;
  63438. _this.blurHPostProcesses = [];
  63439. _this.blurVPostProcesses = [];
  63440. _this.textureAdderPostProcess = null;
  63441. _this.volumetricLightPostProcess = null;
  63442. _this.volumetricLightSmoothXPostProcess = null;
  63443. _this.volumetricLightSmoothYPostProcess = null;
  63444. _this.volumetricLightMergePostProces = null;
  63445. _this.volumetricLightFinalPostProcess = null;
  63446. _this.luminancePostProcess = null;
  63447. _this.luminanceDownSamplePostProcesses = [];
  63448. _this.hdrPostProcess = null;
  63449. _this.textureAdderFinalPostProcess = null;
  63450. _this.lensFlareFinalPostProcess = null;
  63451. _this.hdrFinalPostProcess = null;
  63452. _this.lensFlarePostProcess = null;
  63453. _this.lensFlareComposePostProcess = null;
  63454. _this.motionBlurPostProcess = null;
  63455. _this.depthOfFieldPostProcess = null;
  63456. // Values
  63457. _this.brightThreshold = 1.0;
  63458. _this.blurWidth = 512.0;
  63459. _this.horizontalBlur = false;
  63460. _this.exposure = 1.0;
  63461. _this.lensTexture = null;
  63462. _this.volumetricLightCoefficient = 0.2;
  63463. _this.volumetricLightPower = 4.0;
  63464. _this.volumetricLightBlurScale = 64.0;
  63465. _this.sourceLight = null;
  63466. _this.hdrMinimumLuminance = 1.0;
  63467. _this.hdrDecreaseRate = 0.5;
  63468. _this.hdrIncreaseRate = 0.5;
  63469. _this.lensColorTexture = null;
  63470. _this.lensFlareStrength = 20.0;
  63471. _this.lensFlareGhostDispersal = 1.4;
  63472. _this.lensFlareHaloWidth = 0.7;
  63473. _this.lensFlareDistortionStrength = 16.0;
  63474. _this.lensStarTexture = null;
  63475. _this.lensFlareDirtTexture = null;
  63476. _this.depthOfFieldDistance = 10.0;
  63477. _this.depthOfFieldBlurWidth = 64.0;
  63478. _this.motionStrength = 1.0;
  63479. // IAnimatable
  63480. _this.animations = [];
  63481. _this._currentDepthOfFieldSource = null;
  63482. _this._hdrCurrentLuminance = 1.0;
  63483. // Getters and setters
  63484. _this._bloomEnabled = true;
  63485. _this._depthOfFieldEnabled = false;
  63486. _this._vlsEnabled = false;
  63487. _this._lensFlareEnabled = false;
  63488. _this._hdrEnabled = false;
  63489. _this._motionBlurEnabled = false;
  63490. _this._motionBlurSamples = 64.0;
  63491. _this._volumetricLightStepsCount = 50.0;
  63492. _this._cameras = cameras || [];
  63493. // Initialize
  63494. _this._scene = scene;
  63495. _this._basePostProcess = originalPostProcess;
  63496. _this._ratio = ratio;
  63497. // Misc
  63498. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63499. // Finish
  63500. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63501. _this._buildPipeline();
  63502. return _this;
  63503. }
  63504. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  63505. get: function () {
  63506. return this._bloomEnabled;
  63507. },
  63508. set: function (enabled) {
  63509. if (this._bloomEnabled === enabled) {
  63510. return;
  63511. }
  63512. this._bloomEnabled = enabled;
  63513. this._buildPipeline();
  63514. },
  63515. enumerable: true,
  63516. configurable: true
  63517. });
  63518. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  63519. get: function () {
  63520. return this._depthOfFieldEnabled;
  63521. },
  63522. set: function (enabled) {
  63523. if (this._depthOfFieldEnabled === enabled) {
  63524. return;
  63525. }
  63526. this._depthOfFieldEnabled = enabled;
  63527. this._buildPipeline();
  63528. },
  63529. enumerable: true,
  63530. configurable: true
  63531. });
  63532. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  63533. get: function () {
  63534. return this._lensFlareEnabled;
  63535. },
  63536. set: function (enabled) {
  63537. if (this._lensFlareEnabled === enabled) {
  63538. return;
  63539. }
  63540. this._lensFlareEnabled = enabled;
  63541. this._buildPipeline();
  63542. },
  63543. enumerable: true,
  63544. configurable: true
  63545. });
  63546. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  63547. get: function () {
  63548. return this._hdrEnabled;
  63549. },
  63550. set: function (enabled) {
  63551. if (this._hdrEnabled === enabled) {
  63552. return;
  63553. }
  63554. this._hdrEnabled = enabled;
  63555. this._buildPipeline();
  63556. },
  63557. enumerable: true,
  63558. configurable: true
  63559. });
  63560. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  63561. get: function () {
  63562. return this._vlsEnabled;
  63563. },
  63564. set: function (enabled) {
  63565. if (this._vlsEnabled === enabled) {
  63566. return;
  63567. }
  63568. if (enabled) {
  63569. var geometry = this._scene.enableGeometryBufferRenderer();
  63570. if (!geometry) {
  63571. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  63572. return;
  63573. }
  63574. }
  63575. this._vlsEnabled = enabled;
  63576. this._buildPipeline();
  63577. },
  63578. enumerable: true,
  63579. configurable: true
  63580. });
  63581. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  63582. get: function () {
  63583. return this._motionBlurEnabled;
  63584. },
  63585. set: function (enabled) {
  63586. if (this._motionBlurEnabled === enabled) {
  63587. return;
  63588. }
  63589. this._motionBlurEnabled = enabled;
  63590. this._buildPipeline();
  63591. },
  63592. enumerable: true,
  63593. configurable: true
  63594. });
  63595. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  63596. get: function () {
  63597. return this._volumetricLightStepsCount;
  63598. },
  63599. set: function (count) {
  63600. if (this.volumetricLightPostProcess) {
  63601. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  63602. }
  63603. this._volumetricLightStepsCount = count;
  63604. },
  63605. enumerable: true,
  63606. configurable: true
  63607. });
  63608. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  63609. get: function () {
  63610. return this._motionBlurSamples;
  63611. },
  63612. set: function (samples) {
  63613. if (this.motionBlurPostProcess) {
  63614. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  63615. }
  63616. this._motionBlurSamples = samples;
  63617. },
  63618. enumerable: true,
  63619. configurable: true
  63620. });
  63621. StandardRenderingPipeline.prototype._buildPipeline = function () {
  63622. var _this = this;
  63623. var ratio = this._ratio;
  63624. var scene = this._scene;
  63625. this._disposePostProcesses();
  63626. this._reset();
  63627. // Create pass post-process
  63628. if (!this._basePostProcess) {
  63629. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  63630. this.originalPostProcess.onApply = function (effect) {
  63631. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  63632. };
  63633. }
  63634. else {
  63635. this.originalPostProcess = this._basePostProcess;
  63636. }
  63637. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63638. this._currentDepthOfFieldSource = this.originalPostProcess;
  63639. if (this._vlsEnabled) {
  63640. // Create volumetric light
  63641. this._createVolumetricLightPostProcess(scene, ratio);
  63642. // Create volumetric light final post-process
  63643. 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);
  63644. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  63645. }
  63646. if (this._bloomEnabled) {
  63647. // Create down sample X4 post-process
  63648. this._createDownSampleX4PostProcess(scene, ratio / 2);
  63649. // Create bright pass post-process
  63650. this._createBrightPassPostProcess(scene, ratio / 2);
  63651. // Create gaussian blur post-processes (down sampling blurs)
  63652. this._createBlurPostProcesses(scene, ratio / 4, 1);
  63653. // Create texture adder post-process
  63654. this._createTextureAdderPostProcess(scene, ratio);
  63655. // Create depth-of-field source post-process
  63656. 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);
  63657. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  63658. }
  63659. if (this._lensFlareEnabled) {
  63660. // Create lens flare post-process
  63661. this._createLensFlarePostProcess(scene, ratio);
  63662. // Create depth-of-field source post-process post lens-flare and disable it now
  63663. 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);
  63664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  63665. }
  63666. if (this._hdrEnabled) {
  63667. // Create luminance
  63668. this._createLuminancePostProcesses(scene, this._floatTextureType);
  63669. // Create HDR
  63670. this._createHdrPostProcess(scene, ratio);
  63671. // Create depth-of-field source post-process post hdr and disable it now
  63672. 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);
  63673. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  63674. }
  63675. if (this._depthOfFieldEnabled) {
  63676. // Create gaussian blur used by depth-of-field
  63677. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  63678. // Create depth-of-field post-process
  63679. this._createDepthOfFieldPostProcess(scene, ratio);
  63680. }
  63681. if (this._motionBlurEnabled) {
  63682. // Create motion blur post-process
  63683. this._createMotionBlurPostProcess(scene, ratio);
  63684. }
  63685. if (this._cameras !== null) {
  63686. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63687. }
  63688. };
  63689. // Down Sample X4 Post-Processs
  63690. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  63691. var _this = this;
  63692. var downSampleX4Offsets = new Array(32);
  63693. 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);
  63694. this.downSampleX4PostProcess.onApply = function (effect) {
  63695. var id = 0;
  63696. var width = _this.downSampleX4PostProcess.width;
  63697. var height = _this.downSampleX4PostProcess.height;
  63698. for (var i = -2; i < 2; i++) {
  63699. for (var j = -2; j < 2; j++) {
  63700. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  63701. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  63702. id += 2;
  63703. }
  63704. }
  63705. effect.setArray2("dsOffsets", downSampleX4Offsets);
  63706. };
  63707. // Add to pipeline
  63708. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  63709. };
  63710. // Brightpass Post-Process
  63711. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  63712. var _this = this;
  63713. var brightOffsets = new Array(8);
  63714. 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);
  63715. this.brightPassPostProcess.onApply = function (effect) {
  63716. var sU = (1.0 / _this.brightPassPostProcess.width);
  63717. var sV = (1.0 / _this.brightPassPostProcess.height);
  63718. brightOffsets[0] = -0.5 * sU;
  63719. brightOffsets[1] = 0.5 * sV;
  63720. brightOffsets[2] = 0.5 * sU;
  63721. brightOffsets[3] = 0.5 * sV;
  63722. brightOffsets[4] = -0.5 * sU;
  63723. brightOffsets[5] = -0.5 * sV;
  63724. brightOffsets[6] = 0.5 * sU;
  63725. brightOffsets[7] = -0.5 * sV;
  63726. effect.setArray2("dsOffsets", brightOffsets);
  63727. effect.setFloat("brightThreshold", _this.brightThreshold);
  63728. };
  63729. // Add to pipeline
  63730. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63731. };
  63732. // Create blur H&V post-processes
  63733. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  63734. var _this = this;
  63735. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  63736. var engine = scene.getEngine();
  63737. 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);
  63738. 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);
  63739. blurX.onActivateObservable.add(function () {
  63740. var dw = blurX.width / engine.getRenderWidth();
  63741. blurX.kernel = _this[blurWidthKey] * dw;
  63742. });
  63743. blurY.onActivateObservable.add(function () {
  63744. var dw = blurY.height / engine.getRenderHeight();
  63745. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  63746. });
  63747. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  63748. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  63749. this.blurHPostProcesses.push(blurX);
  63750. this.blurVPostProcesses.push(blurY);
  63751. };
  63752. // Create texture adder post-process
  63753. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63754. var _this = this;
  63755. 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);
  63756. this.textureAdderPostProcess.onApply = function (effect) {
  63757. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  63758. effect.setTexture("lensSampler", _this.lensTexture);
  63759. effect.setFloat("exposure", _this.exposure);
  63760. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  63761. };
  63762. // Add to pipeline
  63763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63764. };
  63765. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  63766. var _this = this;
  63767. var geometryRenderer = scene.enableGeometryBufferRenderer();
  63768. geometryRenderer.enablePosition = true;
  63769. var geometry = geometryRenderer.getGBuffer();
  63770. // Base post-process
  63771. 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));
  63772. var depthValues = BABYLON.Vector2.Zero();
  63773. this.volumetricLightPostProcess.onApply = function (effect) {
  63774. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  63775. var generator = _this.sourceLight.getShadowGenerator();
  63776. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  63777. effect.setTexture("positionSampler", geometry.textures[2]);
  63778. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  63779. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  63780. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  63781. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  63782. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  63783. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  63784. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  63785. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  63786. effect.setVector2("depthValues", depthValues);
  63787. }
  63788. };
  63789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  63790. // Smooth
  63791. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  63792. // Merge
  63793. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  63794. this.volumetricLightMergePostProces.onApply = function (effect) {
  63795. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  63796. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  63797. };
  63798. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  63799. };
  63800. // Create luminance
  63801. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  63802. var _this = this;
  63803. // Create luminance
  63804. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  63805. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  63806. var offsets = [];
  63807. this.luminancePostProcess.onApply = function (effect) {
  63808. var sU = (1.0 / _this.luminancePostProcess.width);
  63809. var sV = (1.0 / _this.luminancePostProcess.height);
  63810. offsets[0] = -0.5 * sU;
  63811. offsets[1] = 0.5 * sV;
  63812. offsets[2] = 0.5 * sU;
  63813. offsets[3] = 0.5 * sV;
  63814. offsets[4] = -0.5 * sU;
  63815. offsets[5] = -0.5 * sV;
  63816. offsets[6] = 0.5 * sU;
  63817. offsets[7] = -0.5 * sV;
  63818. effect.setArray2("lumOffsets", offsets);
  63819. };
  63820. // Add to pipeline
  63821. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  63822. // Create down sample luminance
  63823. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  63824. var size = Math.pow(3, i);
  63825. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  63826. if (i === 0) {
  63827. defines += "#define FINAL_DOWN_SAMPLER";
  63828. }
  63829. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  63830. this.luminanceDownSamplePostProcesses.push(postProcess);
  63831. }
  63832. // Create callbacks and add effects
  63833. var lastLuminance = this.luminancePostProcess;
  63834. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  63835. var downSampleOffsets = new Array(18);
  63836. pp.onApply = function (effect) {
  63837. if (!lastLuminance) {
  63838. return;
  63839. }
  63840. var id = 0;
  63841. for (var x = -1; x < 2; x++) {
  63842. for (var y = -1; y < 2; y++) {
  63843. downSampleOffsets[id] = x / lastLuminance.width;
  63844. downSampleOffsets[id + 1] = y / lastLuminance.height;
  63845. id += 2;
  63846. }
  63847. }
  63848. effect.setArray2("dsOffsets", downSampleOffsets);
  63849. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  63850. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63851. lastLuminance = _this.luminancePostProcess;
  63852. }
  63853. else {
  63854. lastLuminance = pp;
  63855. }
  63856. };
  63857. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63858. pp.onAfterRender = function (effect) {
  63859. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  63860. 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);
  63861. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  63862. };
  63863. }
  63864. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  63865. });
  63866. };
  63867. // Create HDR post-process
  63868. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  63869. var _this = this;
  63870. 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);
  63871. var outputLiminance = 1;
  63872. var time = 0;
  63873. var lastTime = 0;
  63874. this.hdrPostProcess.onApply = function (effect) {
  63875. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  63876. time += scene.getEngine().getDeltaTime();
  63877. if (outputLiminance < 0) {
  63878. outputLiminance = _this._hdrCurrentLuminance;
  63879. }
  63880. else {
  63881. var dt = (lastTime - time) / 1000.0;
  63882. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  63883. outputLiminance += _this.hdrDecreaseRate * dt;
  63884. }
  63885. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  63886. outputLiminance -= _this.hdrIncreaseRate * dt;
  63887. }
  63888. else {
  63889. outputLiminance = _this._hdrCurrentLuminance;
  63890. }
  63891. }
  63892. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  63893. effect.setFloat("averageLuminance", outputLiminance);
  63894. lastTime = time;
  63895. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  63896. };
  63897. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  63898. };
  63899. // Create lens flare post-process
  63900. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  63901. var _this = this;
  63902. 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);
  63903. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  63904. this._createBlurPostProcesses(scene, ratio / 4, 2);
  63905. 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);
  63906. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  63907. var resolution = new BABYLON.Vector2(0, 0);
  63908. // Lens flare
  63909. this.lensFlarePostProcess.onApply = function (effect) {
  63910. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  63911. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  63912. effect.setFloat("strength", _this.lensFlareStrength);
  63913. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  63914. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  63915. // Shift
  63916. resolution.x = _this.lensFlarePostProcess.width;
  63917. resolution.y = _this.lensFlarePostProcess.height;
  63918. effect.setVector2("resolution", resolution);
  63919. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  63920. };
  63921. // Compose
  63922. 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);
  63923. 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);
  63924. this.lensFlareComposePostProcess.onApply = function (effect) {
  63925. if (!_this._scene.activeCamera) {
  63926. return;
  63927. }
  63928. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63929. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  63930. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  63931. // Lens start rotation matrix
  63932. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  63933. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  63934. 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));
  63935. camRot *= 4.0;
  63936. 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);
  63937. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  63938. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  63939. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  63940. };
  63941. };
  63942. // Create depth-of-field post-process
  63943. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  63944. var _this = this;
  63945. 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);
  63946. this.depthOfFieldPostProcess.onApply = function (effect) {
  63947. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63948. effect.setTexture("depthSampler", _this._getDepthTexture());
  63949. effect.setFloat("distance", _this.depthOfFieldDistance);
  63950. };
  63951. // Add to pipeline
  63952. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  63953. };
  63954. // Create motion blur post-process
  63955. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  63956. var _this = this;
  63957. 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);
  63958. var motionScale = 0;
  63959. var prevViewProjection = BABYLON.Matrix.Identity();
  63960. var invViewProjection = BABYLON.Matrix.Identity();
  63961. var viewProjection = BABYLON.Matrix.Identity();
  63962. var screenSize = BABYLON.Vector2.Zero();
  63963. this.motionBlurPostProcess.onApply = function (effect) {
  63964. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  63965. viewProjection.invertToRef(invViewProjection);
  63966. effect.setMatrix("inverseViewProjection", invViewProjection);
  63967. effect.setMatrix("prevViewProjection", prevViewProjection);
  63968. prevViewProjection = viewProjection;
  63969. screenSize.x = _this.motionBlurPostProcess.width;
  63970. screenSize.y = _this.motionBlurPostProcess.height;
  63971. effect.setVector2("screenSize", screenSize);
  63972. motionScale = scene.getEngine().getFps() / 60.0;
  63973. effect.setFloat("motionScale", motionScale);
  63974. effect.setFloat("motionStrength", _this.motionStrength);
  63975. effect.setTexture("depthSampler", _this._getDepthTexture());
  63976. };
  63977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  63978. };
  63979. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  63980. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  63981. var renderer = this._scene.enableGeometryBufferRenderer();
  63982. return renderer.getGBuffer().textures[0];
  63983. }
  63984. return this._scene.enableDepthRenderer().getDepthMap();
  63985. };
  63986. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  63987. for (var i = 0; i < this._cameras.length; i++) {
  63988. var camera = this._cameras[i];
  63989. if (this.originalPostProcess) {
  63990. this.originalPostProcess.dispose(camera);
  63991. }
  63992. if (this.downSampleX4PostProcess) {
  63993. this.downSampleX4PostProcess.dispose(camera);
  63994. }
  63995. if (this.brightPassPostProcess) {
  63996. this.brightPassPostProcess.dispose(camera);
  63997. }
  63998. if (this.textureAdderPostProcess) {
  63999. this.textureAdderPostProcess.dispose(camera);
  64000. }
  64001. if (this.textureAdderFinalPostProcess) {
  64002. this.textureAdderFinalPostProcess.dispose(camera);
  64003. }
  64004. if (this.volumetricLightPostProcess) {
  64005. this.volumetricLightPostProcess.dispose(camera);
  64006. }
  64007. if (this.volumetricLightSmoothXPostProcess) {
  64008. this.volumetricLightSmoothXPostProcess.dispose(camera);
  64009. }
  64010. if (this.volumetricLightSmoothYPostProcess) {
  64011. this.volumetricLightSmoothYPostProcess.dispose(camera);
  64012. }
  64013. if (this.volumetricLightMergePostProces) {
  64014. this.volumetricLightMergePostProces.dispose(camera);
  64015. }
  64016. if (this.volumetricLightFinalPostProcess) {
  64017. this.volumetricLightFinalPostProcess.dispose(camera);
  64018. }
  64019. if (this.lensFlarePostProcess) {
  64020. this.lensFlarePostProcess.dispose(camera);
  64021. }
  64022. if (this.lensFlareComposePostProcess) {
  64023. this.lensFlareComposePostProcess.dispose(camera);
  64024. }
  64025. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  64026. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  64027. }
  64028. if (this.luminancePostProcess) {
  64029. this.luminancePostProcess.dispose(camera);
  64030. }
  64031. if (this.hdrPostProcess) {
  64032. this.hdrPostProcess.dispose(camera);
  64033. }
  64034. if (this.hdrFinalPostProcess) {
  64035. this.hdrFinalPostProcess.dispose(camera);
  64036. }
  64037. if (this.depthOfFieldPostProcess) {
  64038. this.depthOfFieldPostProcess.dispose(camera);
  64039. }
  64040. if (this.motionBlurPostProcess) {
  64041. this.motionBlurPostProcess.dispose(camera);
  64042. }
  64043. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  64044. this.blurHPostProcesses[j].dispose(camera);
  64045. }
  64046. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  64047. this.blurVPostProcesses[j].dispose(camera);
  64048. }
  64049. }
  64050. this.originalPostProcess = null;
  64051. this.downSampleX4PostProcess = null;
  64052. this.brightPassPostProcess = null;
  64053. this.textureAdderPostProcess = null;
  64054. this.textureAdderFinalPostProcess = null;
  64055. this.volumetricLightPostProcess = null;
  64056. this.volumetricLightSmoothXPostProcess = null;
  64057. this.volumetricLightSmoothYPostProcess = null;
  64058. this.volumetricLightMergePostProces = null;
  64059. this.volumetricLightFinalPostProcess = null;
  64060. this.lensFlarePostProcess = null;
  64061. this.lensFlareComposePostProcess = null;
  64062. this.luminancePostProcess = null;
  64063. this.hdrPostProcess = null;
  64064. this.hdrFinalPostProcess = null;
  64065. this.depthOfFieldPostProcess = null;
  64066. this.motionBlurPostProcess = null;
  64067. this.luminanceDownSamplePostProcesses = [];
  64068. this.blurHPostProcesses = [];
  64069. this.blurVPostProcesses = [];
  64070. };
  64071. // Dispose
  64072. StandardRenderingPipeline.prototype.dispose = function () {
  64073. this._disposePostProcesses();
  64074. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64075. _super.prototype.dispose.call(this);
  64076. };
  64077. // Serialize rendering pipeline
  64078. StandardRenderingPipeline.prototype.serialize = function () {
  64079. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64080. serializationObject.customType = "StandardRenderingPipeline";
  64081. return serializationObject;
  64082. };
  64083. /**
  64084. * Static members
  64085. */
  64086. // Parse serialized pipeline
  64087. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64088. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  64089. };
  64090. // Luminance steps
  64091. StandardRenderingPipeline.LuminanceSteps = 6;
  64092. __decorate([
  64093. BABYLON.serialize()
  64094. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  64095. __decorate([
  64096. BABYLON.serialize()
  64097. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  64098. __decorate([
  64099. BABYLON.serialize()
  64100. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  64101. __decorate([
  64102. BABYLON.serialize()
  64103. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  64104. __decorate([
  64105. BABYLON.serializeAsTexture("lensTexture")
  64106. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  64107. __decorate([
  64108. BABYLON.serialize()
  64109. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  64110. __decorate([
  64111. BABYLON.serialize()
  64112. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  64113. __decorate([
  64114. BABYLON.serialize()
  64115. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  64116. __decorate([
  64117. BABYLON.serialize()
  64118. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  64119. __decorate([
  64120. BABYLON.serialize()
  64121. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  64122. __decorate([
  64123. BABYLON.serialize()
  64124. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  64125. __decorate([
  64126. BABYLON.serializeAsTexture("lensColorTexture")
  64127. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  64128. __decorate([
  64129. BABYLON.serialize()
  64130. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  64131. __decorate([
  64132. BABYLON.serialize()
  64133. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  64134. __decorate([
  64135. BABYLON.serialize()
  64136. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  64137. __decorate([
  64138. BABYLON.serialize()
  64139. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  64140. __decorate([
  64141. BABYLON.serializeAsTexture("lensStarTexture")
  64142. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  64143. __decorate([
  64144. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  64145. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  64146. __decorate([
  64147. BABYLON.serialize()
  64148. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  64149. __decorate([
  64150. BABYLON.serialize()
  64151. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  64152. __decorate([
  64153. BABYLON.serialize()
  64154. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  64155. __decorate([
  64156. BABYLON.serialize()
  64157. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  64158. __decorate([
  64159. BABYLON.serialize()
  64160. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  64161. __decorate([
  64162. BABYLON.serialize()
  64163. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  64164. __decorate([
  64165. BABYLON.serialize()
  64166. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  64167. __decorate([
  64168. BABYLON.serialize()
  64169. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  64170. __decorate([
  64171. BABYLON.serialize()
  64172. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  64173. __decorate([
  64174. BABYLON.serialize()
  64175. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  64176. __decorate([
  64177. BABYLON.serialize()
  64178. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  64179. __decorate([
  64180. BABYLON.serialize()
  64181. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  64182. return StandardRenderingPipeline;
  64183. }(BABYLON.PostProcessRenderPipeline));
  64184. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  64185. })(BABYLON || (BABYLON = {}));
  64186. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  64187. var BABYLON;
  64188. (function (BABYLON) {
  64189. var FxaaPostProcess = /** @class */ (function (_super) {
  64190. __extends(FxaaPostProcess, _super);
  64191. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64192. if (camera === void 0) { camera = null; }
  64193. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64194. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  64195. _this.onApplyObservable.add(function (effect) {
  64196. var texelSize = _this.texelSize;
  64197. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  64198. });
  64199. return _this;
  64200. }
  64201. return FxaaPostProcess;
  64202. }(BABYLON.PostProcess));
  64203. BABYLON.FxaaPostProcess = FxaaPostProcess;
  64204. })(BABYLON || (BABYLON = {}));
  64205. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  64206. var BABYLON;
  64207. (function (BABYLON) {
  64208. /**
  64209. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  64210. */
  64211. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  64212. __extends(CircleOfConfusionPostProcess, _super);
  64213. /**
  64214. * Creates a new instance of @see CircleOfConfusionPostProcess
  64215. * @param name The name of the effect.
  64216. * @param scene The scene the effect belongs to.
  64217. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  64218. * @param options The required width/height ratio to downsize to before computing the render pass.
  64219. * @param camera The camera to apply the render pass to.
  64220. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64221. * @param engine The engine which the post process will be applied. (default: current engine)
  64222. * @param reusable If the post process can be reused on the same frame. (default: false)
  64223. * @param textureType Type of textures used when performing the post process. (default: 0)
  64224. */
  64225. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  64226. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64227. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64228. /**
  64229. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  64230. */
  64231. _this.lensSize = 50;
  64232. /**
  64233. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64234. */
  64235. _this.fStop = 1.4;
  64236. /**
  64237. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64238. */
  64239. _this.focusDistance = 2000;
  64240. /**
  64241. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  64242. */
  64243. _this.focalLength = 50;
  64244. _this.onApplyObservable.add(function (effect) {
  64245. effect.setTexture("depthSampler", depthTexture);
  64246. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  64247. var aperture = _this.lensSize / _this.fStop;
  64248. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  64249. effect.setFloat('focusDistance', _this.focusDistance);
  64250. effect.setFloat('cocPrecalculation', cocPrecalculation);
  64251. if (scene.activeCamera) {
  64252. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  64253. }
  64254. });
  64255. return _this;
  64256. }
  64257. return CircleOfConfusionPostProcess;
  64258. }(BABYLON.PostProcess));
  64259. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  64260. })(BABYLON || (BABYLON = {}));
  64261. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  64262. var BABYLON;
  64263. (function (BABYLON) {
  64264. /**
  64265. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  64266. */
  64267. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  64268. __extends(DepthOfFieldMergePostProcess, _super);
  64269. /**
  64270. * Creates a new instance of @see CircleOfConfusionPostProcess
  64271. * @param name The name of the effect.
  64272. * @param original The non-blurred image to be modified
  64273. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  64274. * @param options The required width/height ratio to downsize to before computing the render pass.
  64275. * @param camera The camera to apply the render pass to.
  64276. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64277. * @param engine The engine which the post process will be applied. (default: current engine)
  64278. * @param reusable If the post process can be reused on the same frame. (default: false)
  64279. * @param textureType Type of textures used when performing the post process. (default: 0)
  64280. */
  64281. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, options, camera, samplingMode, engine, reusable, textureType) {
  64282. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64283. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64284. _this.onApplyObservable.add(function (effect) {
  64285. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  64286. effect.setTextureFromPostProcess("originalSampler", original);
  64287. });
  64288. return _this;
  64289. }
  64290. return DepthOfFieldMergePostProcess;
  64291. }(BABYLON.PostProcess));
  64292. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  64293. })(BABYLON || (BABYLON = {}));
  64294. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  64295. var BABYLON;
  64296. (function (BABYLON) {
  64297. /**
  64298. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  64299. */
  64300. var DepthOfFieldEffect = /** @class */ (function (_super) {
  64301. __extends(DepthOfFieldEffect, _super);
  64302. /**
  64303. * Creates a new instance of @see DepthOfFieldEffect
  64304. * @param scene The scene the effect belongs to.
  64305. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  64306. */
  64307. function DepthOfFieldEffect(scene, pipelineTextureType) {
  64308. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  64309. var _this = _super.call(this, scene.getEngine(), "depth of field", function () { return [_this.circleOfConfusion, _this.depthOfFieldPass, _this.depthOfFieldBlurY, _this.depthOfFieldBlurX, _this.depthOfFieldMerge]; }, true) || this;
  64310. // Enable and get current depth map
  64311. var depthMap = scene.enableDepthRenderer().getDepthMap();
  64312. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  64313. _this.circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64314. // Capture circle of confusion texture
  64315. _this.depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64316. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  64317. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  64318. _this.depthOfFieldBlurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), 15, 1.0, null, depthMap, _this.circleOfConfusion, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64319. _this.depthOfFieldBlurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), 15, 1.0, null, depthMap, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64320. // Merge blurred images with original image based on circleOfConfusion
  64321. _this.depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this.circleOfConfusion, _this.depthOfFieldPass, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  64322. return _this;
  64323. }
  64324. Object.defineProperty(DepthOfFieldEffect.prototype, "kernelSize", {
  64325. get: function () {
  64326. return this.depthOfFieldBlurX.kernel;
  64327. },
  64328. /**
  64329. * The size of the kernel to be used for the blur
  64330. */
  64331. set: function (value) {
  64332. this.depthOfFieldBlurX.kernel = value;
  64333. this.depthOfFieldBlurY.kernel = value;
  64334. },
  64335. enumerable: true,
  64336. configurable: true
  64337. });
  64338. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  64339. get: function () {
  64340. return this.circleOfConfusion.focalLength;
  64341. },
  64342. /**
  64343. * The focal the length of the camera used in the effect
  64344. */
  64345. set: function (value) {
  64346. this.circleOfConfusion.focalLength = value;
  64347. },
  64348. enumerable: true,
  64349. configurable: true
  64350. });
  64351. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  64352. get: function () {
  64353. return this.circleOfConfusion.fStop;
  64354. },
  64355. /**
  64356. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  64357. */
  64358. set: function (value) {
  64359. this.circleOfConfusion.fStop = value;
  64360. },
  64361. enumerable: true,
  64362. configurable: true
  64363. });
  64364. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  64365. get: function () {
  64366. return this.circleOfConfusion.focusDistance;
  64367. },
  64368. /**
  64369. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  64370. */
  64371. set: function (value) {
  64372. this.circleOfConfusion.focusDistance = value;
  64373. },
  64374. enumerable: true,
  64375. configurable: true
  64376. });
  64377. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  64378. get: function () {
  64379. return this.circleOfConfusion.lensSize;
  64380. },
  64381. /**
  64382. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  64383. */
  64384. set: function (value) {
  64385. this.circleOfConfusion.lensSize = value;
  64386. },
  64387. enumerable: true,
  64388. configurable: true
  64389. });
  64390. /**
  64391. * Disposes each of the internal effects for a given camera.
  64392. * @param camera The camera to dispose the effect on.
  64393. */
  64394. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  64395. this.depthOfFieldPass.dispose(camera);
  64396. this.circleOfConfusion.dispose(camera);
  64397. this.depthOfFieldBlurX.dispose(camera);
  64398. this.depthOfFieldBlurY.dispose(camera);
  64399. this.depthOfFieldMerge.dispose(camera);
  64400. };
  64401. return DepthOfFieldEffect;
  64402. }(BABYLON.PostProcessRenderEffect));
  64403. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  64404. })(BABYLON || (BABYLON = {}));
  64405. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  64406. var BABYLON;
  64407. (function (BABYLON) {
  64408. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  64409. __extends(DefaultRenderingPipeline, _super);
  64410. /**
  64411. * @constructor
  64412. * @param {string} name - The rendering pipeline name
  64413. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64414. * @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)
  64415. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64416. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  64417. */
  64418. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  64419. if (automaticBuild === void 0) { automaticBuild = true; }
  64420. var _this = _super.call(this, scene.getEngine(), name) || this;
  64421. _this.PassPostProcessId = "PassPostProcessEffect";
  64422. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  64423. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  64424. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  64425. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  64426. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  64427. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  64428. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  64429. // IAnimatable
  64430. _this.animations = [];
  64431. // Values
  64432. _this._bloomEnabled = false;
  64433. _this._depthOfFieldEnabled = false;
  64434. _this._fxaaEnabled = false;
  64435. _this._imageProcessingEnabled = true;
  64436. _this._bloomScale = 0.6;
  64437. _this._buildAllowed = true;
  64438. /**
  64439. * Specifies the size of the bloom blur kernel, relative to the final output size
  64440. */
  64441. _this.bloomKernel = 64;
  64442. /**
  64443. * Specifies the weight of the bloom in the final rendering
  64444. */
  64445. _this._bloomWeight = 0.15;
  64446. _this._cameras = cameras || [];
  64447. _this._buildAllowed = automaticBuild;
  64448. // Initialize
  64449. _this._scene = scene;
  64450. var caps = _this._scene.getEngine().getCaps();
  64451. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  64452. // Misc
  64453. if (_this._hdr) {
  64454. if (caps.textureHalfFloatRender) {
  64455. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64456. }
  64457. else if (caps.textureFloatRender) {
  64458. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64459. }
  64460. }
  64461. else {
  64462. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64463. }
  64464. // Attach
  64465. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64466. _this._buildPipeline();
  64467. return _this;
  64468. }
  64469. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  64470. get: function () {
  64471. return this._bloomWeight;
  64472. },
  64473. set: function (value) {
  64474. if (this._bloomWeight === value) {
  64475. return;
  64476. }
  64477. this._bloomWeight = value;
  64478. if (this._hdr && this.copyBack) {
  64479. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  64480. }
  64481. },
  64482. enumerable: true,
  64483. configurable: true
  64484. });
  64485. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  64486. get: function () {
  64487. return this._bloomScale;
  64488. },
  64489. set: function (value) {
  64490. if (this._bloomScale === value) {
  64491. return;
  64492. }
  64493. this._bloomScale = value;
  64494. this._buildPipeline();
  64495. },
  64496. enumerable: true,
  64497. configurable: true
  64498. });
  64499. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  64500. get: function () {
  64501. return this._bloomEnabled;
  64502. },
  64503. set: function (enabled) {
  64504. if (this._bloomEnabled === enabled) {
  64505. return;
  64506. }
  64507. this._bloomEnabled = enabled;
  64508. this._buildPipeline();
  64509. },
  64510. enumerable: true,
  64511. configurable: true
  64512. });
  64513. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  64514. /**
  64515. * If the depth of field is enabled.
  64516. */
  64517. get: function () {
  64518. return this._depthOfFieldEnabled;
  64519. },
  64520. set: function (enabled) {
  64521. if (this._depthOfFieldEnabled === enabled) {
  64522. return;
  64523. }
  64524. this._depthOfFieldEnabled = enabled;
  64525. this._buildPipeline();
  64526. },
  64527. enumerable: true,
  64528. configurable: true
  64529. });
  64530. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  64531. get: function () {
  64532. return this._fxaaEnabled;
  64533. },
  64534. set: function (enabled) {
  64535. if (this._fxaaEnabled === enabled) {
  64536. return;
  64537. }
  64538. this._fxaaEnabled = enabled;
  64539. this._buildPipeline();
  64540. },
  64541. enumerable: true,
  64542. configurable: true
  64543. });
  64544. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  64545. get: function () {
  64546. return this._imageProcessingEnabled;
  64547. },
  64548. set: function (enabled) {
  64549. if (this._imageProcessingEnabled === enabled) {
  64550. return;
  64551. }
  64552. this._imageProcessingEnabled = enabled;
  64553. this._buildPipeline();
  64554. },
  64555. enumerable: true,
  64556. configurable: true
  64557. });
  64558. /**
  64559. * Force the compilation of the entire pipeline.
  64560. */
  64561. DefaultRenderingPipeline.prototype.prepare = function () {
  64562. var previousState = this._buildAllowed;
  64563. this._buildAllowed = true;
  64564. this._buildPipeline();
  64565. this._buildAllowed = previousState;
  64566. };
  64567. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  64568. var _this = this;
  64569. if (!this._buildAllowed) {
  64570. return;
  64571. }
  64572. var engine = this._scene.getEngine();
  64573. this._disposePostProcesses();
  64574. this._reset();
  64575. if (this.bloomEnabled) {
  64576. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64577. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  64578. if (!this._hdr) {
  64579. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64580. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  64581. this.highlights.autoClear = false;
  64582. this.highlights.alwaysForcePOT = true;
  64583. }
  64584. 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);
  64585. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  64586. this.blurX.alwaysForcePOT = true;
  64587. this.blurX.autoClear = false;
  64588. this.blurX.onActivateObservable.add(function () {
  64589. var dw = _this.blurX.width / engine.getRenderWidth(true);
  64590. _this.blurX.kernel = _this.bloomKernel * dw;
  64591. });
  64592. 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);
  64593. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  64594. this.blurY.alwaysForcePOT = true;
  64595. this.blurY.autoClear = false;
  64596. this.blurY.onActivateObservable.add(function () {
  64597. var dh = _this.blurY.height / engine.getRenderHeight(true);
  64598. _this.blurY.kernel = _this.bloomKernel * dh;
  64599. });
  64600. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64601. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  64602. this.copyBack.alwaysForcePOT = true;
  64603. if (this._hdr) {
  64604. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  64605. var w = this.bloomWeight;
  64606. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  64607. }
  64608. else {
  64609. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  64610. }
  64611. this.copyBack.autoClear = false;
  64612. }
  64613. if (this.depthOfFieldEnabled) {
  64614. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._defaultPipelineTextureType);
  64615. this.addEffect(this.depthOfField);
  64616. }
  64617. if (this._imageProcessingEnabled) {
  64618. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64619. if (this._hdr) {
  64620. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  64621. }
  64622. else {
  64623. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  64624. }
  64625. }
  64626. if (this.fxaaEnabled) {
  64627. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64628. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  64629. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64630. }
  64631. else if (this._hdr && this.imageProcessing) {
  64632. this.finalMerge = this.imageProcessing;
  64633. }
  64634. else {
  64635. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64636. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  64637. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64638. }
  64639. if (this.bloomEnabled) {
  64640. if (this._hdr) {
  64641. this.copyBack.shareOutputWith(this.blurX);
  64642. if (this.imageProcessing) {
  64643. this.imageProcessing.shareOutputWith(this.pass);
  64644. this.imageProcessing.autoClear = false;
  64645. }
  64646. else if (this.fxaa) {
  64647. this.fxaa.shareOutputWith(this.pass);
  64648. }
  64649. else {
  64650. this.finalMerge.shareOutputWith(this.pass);
  64651. }
  64652. }
  64653. else {
  64654. if (this.fxaa) {
  64655. this.fxaa.shareOutputWith(this.pass);
  64656. }
  64657. else {
  64658. this.finalMerge.shareOutputWith(this.pass);
  64659. }
  64660. }
  64661. }
  64662. if (this._cameras !== null) {
  64663. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  64664. }
  64665. };
  64666. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  64667. for (var i = 0; i < this._cameras.length; i++) {
  64668. var camera = this._cameras[i];
  64669. if (this.pass) {
  64670. this.pass.dispose(camera);
  64671. }
  64672. if (this.highlights) {
  64673. this.highlights.dispose(camera);
  64674. }
  64675. if (this.blurX) {
  64676. this.blurX.dispose(camera);
  64677. }
  64678. if (this.blurY) {
  64679. this.blurY.dispose(camera);
  64680. }
  64681. if (this.copyBack) {
  64682. this.copyBack.dispose(camera);
  64683. }
  64684. if (this.imageProcessing) {
  64685. this.imageProcessing.dispose(camera);
  64686. }
  64687. if (this.fxaa) {
  64688. this.fxaa.dispose(camera);
  64689. }
  64690. if (this.finalMerge) {
  64691. this.finalMerge.dispose(camera);
  64692. }
  64693. if (this.depthOfField) {
  64694. this.depthOfField.disposeEffects(camera);
  64695. }
  64696. }
  64697. this.pass = null;
  64698. this.highlights = null;
  64699. this.blurX = null;
  64700. this.blurY = null;
  64701. this.copyBack = null;
  64702. this.imageProcessing = null;
  64703. this.fxaa = null;
  64704. this.finalMerge = null;
  64705. this.depthOfField = null;
  64706. };
  64707. // Dispose
  64708. DefaultRenderingPipeline.prototype.dispose = function () {
  64709. this._disposePostProcesses();
  64710. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64711. _super.prototype.dispose.call(this);
  64712. };
  64713. // Serialize rendering pipeline
  64714. DefaultRenderingPipeline.prototype.serialize = function () {
  64715. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64716. serializationObject.customType = "DefaultRenderingPipeline";
  64717. return serializationObject;
  64718. };
  64719. // Parse serialized pipeline
  64720. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64721. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  64722. };
  64723. __decorate([
  64724. BABYLON.serialize()
  64725. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  64726. __decorate([
  64727. BABYLON.serialize()
  64728. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  64729. __decorate([
  64730. BABYLON.serialize()
  64731. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  64732. __decorate([
  64733. BABYLON.serialize()
  64734. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  64735. __decorate([
  64736. BABYLON.serialize()
  64737. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  64738. __decorate([
  64739. BABYLON.serialize()
  64740. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  64741. __decorate([
  64742. BABYLON.serialize()
  64743. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  64744. __decorate([
  64745. BABYLON.serialize()
  64746. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  64747. __decorate([
  64748. BABYLON.serialize()
  64749. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  64750. return DefaultRenderingPipeline;
  64751. }(BABYLON.PostProcessRenderPipeline));
  64752. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  64753. })(BABYLON || (BABYLON = {}));
  64754. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  64755. var BABYLON;
  64756. (function (BABYLON) {
  64757. /**
  64758. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  64759. */
  64760. var GeometryBufferRenderer = /** @class */ (function () {
  64761. /**
  64762. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  64763. * @param scene The scene the buffer belongs to
  64764. * @param ratio How big is the buffer related to the main canvas.
  64765. */
  64766. function GeometryBufferRenderer(scene, ratio) {
  64767. if (ratio === void 0) { ratio = 1; }
  64768. this._enablePosition = false;
  64769. this._scene = scene;
  64770. this._ratio = ratio;
  64771. // Render target
  64772. this._createRenderTargets();
  64773. }
  64774. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  64775. /**
  64776. * Set the render list (meshes to be rendered) used in the G buffer.
  64777. */
  64778. set: function (meshes) {
  64779. this._multiRenderTarget.renderList = meshes;
  64780. },
  64781. enumerable: true,
  64782. configurable: true
  64783. });
  64784. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  64785. /**
  64786. * Gets wether or not G buffer are supported by the running hardware.
  64787. * This requires draw buffer supports
  64788. */
  64789. get: function () {
  64790. return this._multiRenderTarget.isSupported;
  64791. },
  64792. enumerable: true,
  64793. configurable: true
  64794. });
  64795. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  64796. /**
  64797. * Gets wether or not position are enabled for the G buffer.
  64798. */
  64799. get: function () {
  64800. return this._enablePosition;
  64801. },
  64802. /**
  64803. * Sets wether or not position are enabled for the G buffer.
  64804. */
  64805. set: function (enable) {
  64806. this._enablePosition = enable;
  64807. this.dispose();
  64808. this._createRenderTargets();
  64809. },
  64810. enumerable: true,
  64811. configurable: true
  64812. });
  64813. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  64814. /**
  64815. * Gets the scene associated with the buffer.
  64816. */
  64817. get: function () {
  64818. return this._scene;
  64819. },
  64820. enumerable: true,
  64821. configurable: true
  64822. });
  64823. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  64824. /**
  64825. * Gets the ratio used by the buffer during its creation.
  64826. * How big is the buffer related to the main canvas.
  64827. */
  64828. get: function () {
  64829. return this._ratio;
  64830. },
  64831. enumerable: true,
  64832. configurable: true
  64833. });
  64834. /**
  64835. * Checks wether everything is ready to render a submesh to the G buffer.
  64836. * @param subMesh the submesh to check readiness for
  64837. * @param useInstances is the mesh drawn using instance or not
  64838. * @returns true if ready otherwise false
  64839. */
  64840. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  64841. var material = subMesh.getMaterial();
  64842. if (material && material.disableDepthWrite) {
  64843. return false;
  64844. }
  64845. var defines = [];
  64846. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  64847. var mesh = subMesh.getMesh();
  64848. // Alpha test
  64849. if (material && material.needAlphaTesting()) {
  64850. defines.push("#define ALPHATEST");
  64851. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64852. attribs.push(BABYLON.VertexBuffer.UVKind);
  64853. defines.push("#define UV1");
  64854. }
  64855. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64856. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64857. defines.push("#define UV2");
  64858. }
  64859. }
  64860. // Buffers
  64861. if (this._enablePosition) {
  64862. defines.push("#define POSITION");
  64863. }
  64864. // Bones
  64865. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64866. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64867. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64868. if (mesh.numBoneInfluencers > 4) {
  64869. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64870. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64871. }
  64872. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64873. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64874. }
  64875. else {
  64876. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64877. }
  64878. // Instances
  64879. if (useInstances) {
  64880. defines.push("#define INSTANCES");
  64881. attribs.push("world0");
  64882. attribs.push("world1");
  64883. attribs.push("world2");
  64884. attribs.push("world3");
  64885. }
  64886. // Get correct effect
  64887. var join = defines.join("\n");
  64888. if (this._cachedDefines !== join) {
  64889. this._cachedDefines = join;
  64890. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  64891. }
  64892. return this._effect.isReady();
  64893. };
  64894. /**
  64895. * Gets the current underlying G Buffer.
  64896. * @returns the buffer
  64897. */
  64898. GeometryBufferRenderer.prototype.getGBuffer = function () {
  64899. return this._multiRenderTarget;
  64900. };
  64901. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  64902. /**
  64903. * Gets the number of samples used to render the buffer (anti aliasing).
  64904. */
  64905. get: function () {
  64906. return this._multiRenderTarget.samples;
  64907. },
  64908. /**
  64909. * Sets the number of samples used to render the buffer (anti aliasing).
  64910. */
  64911. set: function (value) {
  64912. this._multiRenderTarget.samples = value;
  64913. },
  64914. enumerable: true,
  64915. configurable: true
  64916. });
  64917. /**
  64918. * Disposes the renderer and frees up associated resources.
  64919. */
  64920. GeometryBufferRenderer.prototype.dispose = function () {
  64921. this.getGBuffer().dispose();
  64922. };
  64923. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  64924. var _this = this;
  64925. var engine = this._scene.getEngine();
  64926. var count = this._enablePosition ? 3 : 2;
  64927. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  64928. if (!this.isSupported) {
  64929. return;
  64930. }
  64931. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64932. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64933. this._multiRenderTarget.refreshRate = 1;
  64934. this._multiRenderTarget.renderParticles = false;
  64935. this._multiRenderTarget.renderList = null;
  64936. // set default depth value to 1.0 (far away)
  64937. this._multiRenderTarget.onClearObservable.add(function (engine) {
  64938. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  64939. });
  64940. // Custom render function
  64941. var renderSubMesh = function (subMesh) {
  64942. var mesh = subMesh.getRenderingMesh();
  64943. var scene = _this._scene;
  64944. var engine = scene.getEngine();
  64945. var material = subMesh.getMaterial();
  64946. if (!material) {
  64947. return;
  64948. }
  64949. // Culling
  64950. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64951. // Managing instances
  64952. var batch = mesh._getInstancesRenderList(subMesh._id);
  64953. if (batch.mustReturn) {
  64954. return;
  64955. }
  64956. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64957. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  64958. engine.enableEffect(_this._effect);
  64959. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64960. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64961. _this._effect.setMatrix("view", scene.getViewMatrix());
  64962. // Alpha test
  64963. if (material && material.needAlphaTesting()) {
  64964. var alphaTexture = material.getAlphaTestTexture();
  64965. if (alphaTexture) {
  64966. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64967. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64968. }
  64969. }
  64970. // Bones
  64971. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64972. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64973. }
  64974. // Draw
  64975. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64976. }
  64977. };
  64978. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64979. var index;
  64980. if (depthOnlySubMeshes.length) {
  64981. engine.setColorWrite(false);
  64982. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64983. renderSubMesh(depthOnlySubMeshes.data[index]);
  64984. }
  64985. engine.setColorWrite(true);
  64986. }
  64987. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64988. renderSubMesh(opaqueSubMeshes.data[index]);
  64989. }
  64990. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64991. renderSubMesh(alphaTestSubMeshes.data[index]);
  64992. }
  64993. };
  64994. };
  64995. return GeometryBufferRenderer;
  64996. }());
  64997. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  64998. })(BABYLON || (BABYLON = {}));
  64999. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  65000. var BABYLON;
  65001. (function (BABYLON) {
  65002. var RefractionPostProcess = /** @class */ (function (_super) {
  65003. __extends(RefractionPostProcess, _super);
  65004. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  65005. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  65006. _this.color = color;
  65007. _this.depth = depth;
  65008. _this.colorLevel = colorLevel;
  65009. _this.onActivateObservable.add(function (cam) {
  65010. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  65011. });
  65012. _this.onApplyObservable.add(function (effect) {
  65013. effect.setColor3("baseColor", _this.color);
  65014. effect.setFloat("depth", _this.depth);
  65015. effect.setFloat("colorLevel", _this.colorLevel);
  65016. effect.setTexture("refractionSampler", _this._refRexture);
  65017. });
  65018. return _this;
  65019. }
  65020. // Methods
  65021. RefractionPostProcess.prototype.dispose = function (camera) {
  65022. if (this._refRexture) {
  65023. this._refRexture.dispose();
  65024. }
  65025. _super.prototype.dispose.call(this, camera);
  65026. };
  65027. return RefractionPostProcess;
  65028. }(BABYLON.PostProcess));
  65029. BABYLON.RefractionPostProcess = RefractionPostProcess;
  65030. })(BABYLON || (BABYLON = {}));
  65031. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  65032. var BABYLON;
  65033. (function (BABYLON) {
  65034. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  65035. __extends(BlackAndWhitePostProcess, _super);
  65036. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  65037. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  65038. _this.degree = 1;
  65039. _this.onApplyObservable.add(function (effect) {
  65040. effect.setFloat("degree", _this.degree);
  65041. });
  65042. return _this;
  65043. }
  65044. return BlackAndWhitePostProcess;
  65045. }(BABYLON.PostProcess));
  65046. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  65047. })(BABYLON || (BABYLON = {}));
  65048. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  65049. var BABYLON;
  65050. (function (BABYLON) {
  65051. var ConvolutionPostProcess = /** @class */ (function (_super) {
  65052. __extends(ConvolutionPostProcess, _super);
  65053. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  65054. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  65055. _this.kernel = kernel;
  65056. _this.onApply = function (effect) {
  65057. effect.setFloat2("screenSize", _this.width, _this.height);
  65058. effect.setArray("kernel", _this.kernel);
  65059. };
  65060. return _this;
  65061. }
  65062. // Statics
  65063. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  65064. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  65065. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  65066. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  65067. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  65068. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  65069. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  65070. return ConvolutionPostProcess;
  65071. }(BABYLON.PostProcess));
  65072. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  65073. })(BABYLON || (BABYLON = {}));
  65074. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  65075. var BABYLON;
  65076. (function (BABYLON) {
  65077. var FilterPostProcess = /** @class */ (function (_super) {
  65078. __extends(FilterPostProcess, _super);
  65079. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  65080. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  65081. _this.kernelMatrix = kernelMatrix;
  65082. _this.onApply = function (effect) {
  65083. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  65084. };
  65085. return _this;
  65086. }
  65087. return FilterPostProcess;
  65088. }(BABYLON.PostProcess));
  65089. BABYLON.FilterPostProcess = FilterPostProcess;
  65090. })(BABYLON || (BABYLON = {}));
  65091. //# sourceMappingURL=babylon.filterPostProcess.js.map
  65092. var BABYLON;
  65093. (function (BABYLON) {
  65094. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  65095. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  65096. __extends(VolumetricLightScatteringPostProcess, _super);
  65097. /**
  65098. * @constructor
  65099. * @param {string} name - The post-process name
  65100. * @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)
  65101. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  65102. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  65103. * @param {number} samples - The post-process quality, default 100
  65104. * @param {number} samplingMode - The post-process filtering mode
  65105. * @param {BABYLON.Engine} engine - The babylon engine
  65106. * @param {boolean} reusable - If the post-process is reusable
  65107. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  65108. */
  65109. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  65110. if (samples === void 0) { samples = 100; }
  65111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65112. 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;
  65113. _this._screenCoordinates = BABYLON.Vector2.Zero();
  65114. /**
  65115. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  65116. * @type {Vector3}
  65117. */
  65118. _this.customMeshPosition = BABYLON.Vector3.Zero();
  65119. /**
  65120. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  65121. * @type {boolean}
  65122. */
  65123. _this.useCustomMeshPosition = false;
  65124. /**
  65125. * If the post-process should inverse the light scattering direction
  65126. * @type {boolean}
  65127. */
  65128. _this.invert = true;
  65129. /**
  65130. * Array containing the excluded meshes not rendered in the internal pass
  65131. */
  65132. _this.excludedMeshes = new Array();
  65133. /**
  65134. * Controls the overall intensity of the post-process
  65135. * @type {number}
  65136. */
  65137. _this.exposure = 0.3;
  65138. /**
  65139. * Dissipates each sample's contribution in range [0, 1]
  65140. * @type {number}
  65141. */
  65142. _this.decay = 0.96815;
  65143. /**
  65144. * Controls the overall intensity of each sample
  65145. * @type {number}
  65146. */
  65147. _this.weight = 0.58767;
  65148. /**
  65149. * Controls the density of each sample
  65150. * @type {number}
  65151. */
  65152. _this.density = 0.926;
  65153. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  65154. engine = scene.getEngine();
  65155. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  65156. // Configure mesh
  65157. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  65158. // Configure
  65159. _this._createPass(scene, ratio.passRatio || ratio);
  65160. _this.onActivate = function (camera) {
  65161. if (!_this.isSupported) {
  65162. _this.dispose(camera);
  65163. }
  65164. _this.onActivate = null;
  65165. };
  65166. _this.onApplyObservable.add(function (effect) {
  65167. _this._updateMeshScreenCoordinates(scene);
  65168. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  65169. effect.setFloat("exposure", _this.exposure);
  65170. effect.setFloat("decay", _this.decay);
  65171. effect.setFloat("weight", _this.weight);
  65172. effect.setFloat("density", _this.density);
  65173. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  65174. });
  65175. return _this;
  65176. }
  65177. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  65178. get: function () {
  65179. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65180. return false;
  65181. },
  65182. set: function (useDiffuseColor) {
  65183. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  65184. },
  65185. enumerable: true,
  65186. configurable: true
  65187. });
  65188. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  65189. return "VolumetricLightScatteringPostProcess";
  65190. };
  65191. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  65192. var mesh = subMesh.getMesh();
  65193. // Render this.mesh as default
  65194. if (mesh === this.mesh && mesh.material) {
  65195. return mesh.material.isReady(mesh);
  65196. }
  65197. var defines = [];
  65198. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65199. var material = subMesh.getMaterial();
  65200. // Alpha test
  65201. if (material) {
  65202. if (material.needAlphaTesting()) {
  65203. defines.push("#define ALPHATEST");
  65204. }
  65205. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65206. attribs.push(BABYLON.VertexBuffer.UVKind);
  65207. defines.push("#define UV1");
  65208. }
  65209. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65210. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65211. defines.push("#define UV2");
  65212. }
  65213. }
  65214. // Bones
  65215. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65216. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65217. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65218. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65219. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  65220. }
  65221. else {
  65222. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65223. }
  65224. // Instances
  65225. if (useInstances) {
  65226. defines.push("#define INSTANCES");
  65227. attribs.push("world0");
  65228. attribs.push("world1");
  65229. attribs.push("world2");
  65230. attribs.push("world3");
  65231. }
  65232. // Get correct effect
  65233. var join = defines.join("\n");
  65234. if (this._cachedDefines !== join) {
  65235. this._cachedDefines = join;
  65236. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  65237. }
  65238. return this._volumetricLightScatteringPass.isReady();
  65239. };
  65240. /**
  65241. * Sets the new light position for light scattering effect
  65242. * @param {BABYLON.Vector3} The new custom light position
  65243. */
  65244. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  65245. this.customMeshPosition = position;
  65246. };
  65247. /**
  65248. * Returns the light position for light scattering effect
  65249. * @return {BABYLON.Vector3} The custom light position
  65250. */
  65251. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  65252. return this.customMeshPosition;
  65253. };
  65254. /**
  65255. * Disposes the internal assets and detaches the post-process from the camera
  65256. */
  65257. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  65258. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  65259. if (rttIndex !== -1) {
  65260. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  65261. }
  65262. this._volumetricLightScatteringRTT.dispose();
  65263. _super.prototype.dispose.call(this, camera);
  65264. };
  65265. /**
  65266. * Returns the render target texture used by the post-process
  65267. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  65268. */
  65269. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  65270. return this._volumetricLightScatteringRTT;
  65271. };
  65272. // Private methods
  65273. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  65274. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  65275. return true;
  65276. }
  65277. return false;
  65278. };
  65279. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  65280. var _this = this;
  65281. var engine = scene.getEngine();
  65282. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65283. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65284. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65285. this._volumetricLightScatteringRTT.renderList = null;
  65286. this._volumetricLightScatteringRTT.renderParticles = false;
  65287. var camera = this.getCamera();
  65288. if (camera) {
  65289. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65290. }
  65291. else {
  65292. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  65293. }
  65294. // Custom render function for submeshes
  65295. var renderSubMesh = function (subMesh) {
  65296. var mesh = subMesh.getRenderingMesh();
  65297. if (_this._meshExcluded(mesh)) {
  65298. return;
  65299. }
  65300. var material = subMesh.getMaterial();
  65301. if (!material) {
  65302. return;
  65303. }
  65304. var scene = mesh.getScene();
  65305. var engine = scene.getEngine();
  65306. // Culling
  65307. engine.setState(material.backFaceCulling);
  65308. // Managing instances
  65309. var batch = mesh._getInstancesRenderList(subMesh._id);
  65310. if (batch.mustReturn) {
  65311. return;
  65312. }
  65313. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65314. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  65315. var effect = _this._volumetricLightScatteringPass;
  65316. if (mesh === _this.mesh) {
  65317. if (subMesh.effect) {
  65318. effect = subMesh.effect;
  65319. }
  65320. else {
  65321. effect = material.getEffect();
  65322. }
  65323. }
  65324. engine.enableEffect(effect);
  65325. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  65326. if (mesh === _this.mesh) {
  65327. material.bind(mesh.getWorldMatrix(), mesh);
  65328. }
  65329. else {
  65330. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  65331. // Alpha test
  65332. if (material && material.needAlphaTesting()) {
  65333. var alphaTexture = material.getAlphaTestTexture();
  65334. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  65335. if (alphaTexture) {
  65336. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65337. }
  65338. }
  65339. // Bones
  65340. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65341. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65342. }
  65343. }
  65344. // Draw
  65345. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  65346. }
  65347. };
  65348. // Render target texture callbacks
  65349. var savedSceneClearColor;
  65350. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  65351. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  65352. savedSceneClearColor = scene.clearColor;
  65353. scene.clearColor = sceneClearColor;
  65354. });
  65355. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  65356. scene.clearColor = savedSceneClearColor;
  65357. });
  65358. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65359. var engine = scene.getEngine();
  65360. var index;
  65361. if (depthOnlySubMeshes.length) {
  65362. engine.setColorWrite(false);
  65363. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65364. renderSubMesh(depthOnlySubMeshes.data[index]);
  65365. }
  65366. engine.setColorWrite(true);
  65367. }
  65368. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65369. renderSubMesh(opaqueSubMeshes.data[index]);
  65370. }
  65371. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65372. renderSubMesh(alphaTestSubMeshes.data[index]);
  65373. }
  65374. if (transparentSubMeshes.length) {
  65375. // Sort sub meshes
  65376. for (index = 0; index < transparentSubMeshes.length; index++) {
  65377. var submesh = transparentSubMeshes.data[index];
  65378. var boundingInfo = submesh.getBoundingInfo();
  65379. if (boundingInfo && scene.activeCamera) {
  65380. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  65381. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  65382. }
  65383. }
  65384. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  65385. sortedArray.sort(function (a, b) {
  65386. // Alpha index first
  65387. if (a._alphaIndex > b._alphaIndex) {
  65388. return 1;
  65389. }
  65390. if (a._alphaIndex < b._alphaIndex) {
  65391. return -1;
  65392. }
  65393. // Then distance to camera
  65394. if (a._distanceToCamera < b._distanceToCamera) {
  65395. return 1;
  65396. }
  65397. if (a._distanceToCamera > b._distanceToCamera) {
  65398. return -1;
  65399. }
  65400. return 0;
  65401. });
  65402. // Render sub meshes
  65403. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65404. for (index = 0; index < sortedArray.length; index++) {
  65405. renderSubMesh(sortedArray[index]);
  65406. }
  65407. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65408. }
  65409. };
  65410. };
  65411. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  65412. var transform = scene.getTransformMatrix();
  65413. var meshPosition;
  65414. if (this.useCustomMeshPosition) {
  65415. meshPosition = this.customMeshPosition;
  65416. }
  65417. else if (this.attachedNode) {
  65418. meshPosition = this.attachedNode.position;
  65419. }
  65420. else {
  65421. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  65422. }
  65423. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  65424. this._screenCoordinates.x = pos.x / this._viewPort.width;
  65425. this._screenCoordinates.y = pos.y / this._viewPort.height;
  65426. if (this.invert)
  65427. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  65428. };
  65429. // Static methods
  65430. /**
  65431. * Creates a default mesh for the Volumeric Light Scattering post-process
  65432. * @param {string} The mesh name
  65433. * @param {BABYLON.Scene} The scene where to create the mesh
  65434. * @return {BABYLON.Mesh} the default mesh
  65435. */
  65436. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  65437. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  65438. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  65439. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  65440. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  65441. mesh.material = material;
  65442. return mesh;
  65443. };
  65444. __decorate([
  65445. BABYLON.serializeAsVector3()
  65446. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  65447. __decorate([
  65448. BABYLON.serialize()
  65449. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  65450. __decorate([
  65451. BABYLON.serialize()
  65452. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  65453. __decorate([
  65454. BABYLON.serializeAsMeshReference()
  65455. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  65456. __decorate([
  65457. BABYLON.serialize()
  65458. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  65459. __decorate([
  65460. BABYLON.serialize()
  65461. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  65462. __decorate([
  65463. BABYLON.serialize()
  65464. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  65465. __decorate([
  65466. BABYLON.serialize()
  65467. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  65468. __decorate([
  65469. BABYLON.serialize()
  65470. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  65471. return VolumetricLightScatteringPostProcess;
  65472. }(BABYLON.PostProcess));
  65473. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  65474. })(BABYLON || (BABYLON = {}));
  65475. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  65476. //
  65477. // This post-process allows the modification of rendered colors by using
  65478. // a 'look-up table' (LUT). This effect is also called Color Grading.
  65479. //
  65480. // The object needs to be provided an url to a texture containing the color
  65481. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  65482. // Use an image editing software to tweak the LUT to match your needs.
  65483. //
  65484. // For an example of a color LUT, see here:
  65485. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  65486. // For explanations on color grading, see here:
  65487. // http://udn.epicgames.com/Three/ColorGrading.html
  65488. //
  65489. var BABYLON;
  65490. (function (BABYLON) {
  65491. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  65492. __extends(ColorCorrectionPostProcess, _super);
  65493. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  65494. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  65495. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65496. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  65497. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65498. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65499. _this.onApply = function (effect) {
  65500. effect.setTexture("colorTable", _this._colorTableTexture);
  65501. };
  65502. return _this;
  65503. }
  65504. return ColorCorrectionPostProcess;
  65505. }(BABYLON.PostProcess));
  65506. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  65507. })(BABYLON || (BABYLON = {}));
  65508. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  65509. var BABYLON;
  65510. (function (BABYLON) {
  65511. var TonemappingOperator;
  65512. (function (TonemappingOperator) {
  65513. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  65514. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  65515. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  65516. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  65517. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  65518. ;
  65519. var TonemapPostProcess = /** @class */ (function (_super) {
  65520. __extends(TonemapPostProcess, _super);
  65521. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  65522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65523. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65524. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  65525. _this._operator = _operator;
  65526. _this.exposureAdjustment = exposureAdjustment;
  65527. var defines = "#define ";
  65528. if (_this._operator === TonemappingOperator.Hable)
  65529. defines += "HABLE_TONEMAPPING";
  65530. else if (_this._operator === TonemappingOperator.Reinhard)
  65531. defines += "REINHARD_TONEMAPPING";
  65532. else if (_this._operator === TonemappingOperator.HejiDawson)
  65533. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  65534. else if (_this._operator === TonemappingOperator.Photographic)
  65535. defines += "PHOTOGRAPHIC_TONEMAPPING";
  65536. //sadly a second call to create the effect.
  65537. _this.updateEffect(defines);
  65538. _this.onApply = function (effect) {
  65539. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  65540. };
  65541. return _this;
  65542. }
  65543. return TonemapPostProcess;
  65544. }(BABYLON.PostProcess));
  65545. BABYLON.TonemapPostProcess = TonemapPostProcess;
  65546. })(BABYLON || (BABYLON = {}));
  65547. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  65548. var BABYLON;
  65549. (function (BABYLON) {
  65550. var DisplayPassPostProcess = /** @class */ (function (_super) {
  65551. __extends(DisplayPassPostProcess, _super);
  65552. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  65553. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  65554. }
  65555. return DisplayPassPostProcess;
  65556. }(BABYLON.PostProcess));
  65557. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  65558. })(BABYLON || (BABYLON = {}));
  65559. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  65560. var BABYLON;
  65561. (function (BABYLON) {
  65562. var HighlightsPostProcess = /** @class */ (function (_super) {
  65563. __extends(HighlightsPostProcess, _super);
  65564. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  65565. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65566. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  65567. }
  65568. return HighlightsPostProcess;
  65569. }(BABYLON.PostProcess));
  65570. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  65571. })(BABYLON || (BABYLON = {}));
  65572. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  65573. var BABYLON;
  65574. (function (BABYLON) {
  65575. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  65576. __extends(ImageProcessingPostProcess, _super);
  65577. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  65578. if (camera === void 0) { camera = null; }
  65579. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65580. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  65581. _this._fromLinearSpace = true;
  65582. /**
  65583. * Defines cache preventing GC.
  65584. */
  65585. _this._defines = {
  65586. IMAGEPROCESSING: false,
  65587. VIGNETTE: false,
  65588. VIGNETTEBLENDMODEMULTIPLY: false,
  65589. VIGNETTEBLENDMODEOPAQUE: false,
  65590. TONEMAPPING: false,
  65591. CONTRAST: false,
  65592. COLORCURVES: false,
  65593. COLORGRADING: false,
  65594. COLORGRADING3D: false,
  65595. FROMLINEARSPACE: false,
  65596. SAMPLER3DGREENDEPTH: false,
  65597. SAMPLER3DBGRMAP: false,
  65598. IMAGEPROCESSINGPOSTPROCESS: false,
  65599. EXPOSURE: false,
  65600. };
  65601. // Setup the configuration as forced by the constructor. This would then not force the
  65602. // scene materials output in linear space and let untouched the default forward pass.
  65603. if (imageProcessingConfiguration) {
  65604. imageProcessingConfiguration.applyByPostProcess = true;
  65605. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  65606. // This will cause the shader to be compiled
  65607. _this.fromLinearSpace = false;
  65608. }
  65609. else {
  65610. _this._attachImageProcessingConfiguration(null, true);
  65611. _this.imageProcessingConfiguration.applyByPostProcess = true;
  65612. }
  65613. _this.onApply = function (effect) {
  65614. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  65615. };
  65616. return _this;
  65617. }
  65618. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  65619. /**
  65620. * Gets the image processing configuration used either in this material.
  65621. */
  65622. get: function () {
  65623. return this._imageProcessingConfiguration;
  65624. },
  65625. /**
  65626. * Sets the Default image processing configuration used either in the this material.
  65627. *
  65628. * If sets to null, the scene one is in use.
  65629. */
  65630. set: function (value) {
  65631. this._attachImageProcessingConfiguration(value);
  65632. },
  65633. enumerable: true,
  65634. configurable: true
  65635. });
  65636. /**
  65637. * Attaches a new image processing configuration to the PBR Material.
  65638. * @param configuration
  65639. */
  65640. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  65641. var _this = this;
  65642. if (doNotBuild === void 0) { doNotBuild = false; }
  65643. if (configuration === this._imageProcessingConfiguration) {
  65644. return;
  65645. }
  65646. // Detaches observer.
  65647. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65648. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65649. }
  65650. // Pick the scene configuration if needed.
  65651. if (!configuration) {
  65652. var scene = null;
  65653. var engine = this.getEngine();
  65654. var camera = this.getCamera();
  65655. if (camera) {
  65656. scene = camera.getScene();
  65657. }
  65658. else if (engine && engine.scenes) {
  65659. var scenes = engine.scenes;
  65660. scene = scenes[scenes.length - 1];
  65661. }
  65662. else {
  65663. scene = BABYLON.Engine.LastCreatedScene;
  65664. }
  65665. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  65666. }
  65667. else {
  65668. this._imageProcessingConfiguration = configuration;
  65669. }
  65670. // Attaches observer.
  65671. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  65672. _this._updateParameters();
  65673. });
  65674. // Ensure the effect will be rebuilt.
  65675. if (!doNotBuild) {
  65676. this._updateParameters();
  65677. }
  65678. };
  65679. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  65680. /**
  65681. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65682. */
  65683. get: function () {
  65684. return this.imageProcessingConfiguration.colorCurves;
  65685. },
  65686. /**
  65687. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65688. */
  65689. set: function (value) {
  65690. this.imageProcessingConfiguration.colorCurves = value;
  65691. },
  65692. enumerable: true,
  65693. configurable: true
  65694. });
  65695. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  65696. /**
  65697. * Gets wether the color curves effect is enabled.
  65698. */
  65699. get: function () {
  65700. return this.imageProcessingConfiguration.colorCurvesEnabled;
  65701. },
  65702. /**
  65703. * Sets wether the color curves effect is enabled.
  65704. */
  65705. set: function (value) {
  65706. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  65707. },
  65708. enumerable: true,
  65709. configurable: true
  65710. });
  65711. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  65712. /**
  65713. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65714. */
  65715. get: function () {
  65716. return this.imageProcessingConfiguration.colorGradingTexture;
  65717. },
  65718. /**
  65719. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65720. */
  65721. set: function (value) {
  65722. this.imageProcessingConfiguration.colorGradingTexture = value;
  65723. },
  65724. enumerable: true,
  65725. configurable: true
  65726. });
  65727. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  65728. /**
  65729. * Gets wether the color grading effect is enabled.
  65730. */
  65731. get: function () {
  65732. return this.imageProcessingConfiguration.colorGradingEnabled;
  65733. },
  65734. /**
  65735. * Gets wether the color grading effect is enabled.
  65736. */
  65737. set: function (value) {
  65738. this.imageProcessingConfiguration.colorGradingEnabled = value;
  65739. },
  65740. enumerable: true,
  65741. configurable: true
  65742. });
  65743. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  65744. /**
  65745. * Gets exposure used in the effect.
  65746. */
  65747. get: function () {
  65748. return this.imageProcessingConfiguration.exposure;
  65749. },
  65750. /**
  65751. * Sets exposure used in the effect.
  65752. */
  65753. set: function (value) {
  65754. this.imageProcessingConfiguration.exposure = value;
  65755. },
  65756. enumerable: true,
  65757. configurable: true
  65758. });
  65759. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  65760. /**
  65761. * Gets wether tonemapping is enabled or not.
  65762. */
  65763. get: function () {
  65764. return this._imageProcessingConfiguration.toneMappingEnabled;
  65765. },
  65766. /**
  65767. * Sets wether tonemapping is enabled or not
  65768. */
  65769. set: function (value) {
  65770. this._imageProcessingConfiguration.toneMappingEnabled = value;
  65771. },
  65772. enumerable: true,
  65773. configurable: true
  65774. });
  65775. ;
  65776. ;
  65777. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  65778. /**
  65779. * Gets contrast used in the effect.
  65780. */
  65781. get: function () {
  65782. return this.imageProcessingConfiguration.contrast;
  65783. },
  65784. /**
  65785. * Sets contrast used in the effect.
  65786. */
  65787. set: function (value) {
  65788. this.imageProcessingConfiguration.contrast = value;
  65789. },
  65790. enumerable: true,
  65791. configurable: true
  65792. });
  65793. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  65794. /**
  65795. * Gets Vignette stretch size.
  65796. */
  65797. get: function () {
  65798. return this.imageProcessingConfiguration.vignetteStretch;
  65799. },
  65800. /**
  65801. * Sets Vignette stretch size.
  65802. */
  65803. set: function (value) {
  65804. this.imageProcessingConfiguration.vignetteStretch = value;
  65805. },
  65806. enumerable: true,
  65807. configurable: true
  65808. });
  65809. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  65810. /**
  65811. * Gets Vignette centre X Offset.
  65812. */
  65813. get: function () {
  65814. return this.imageProcessingConfiguration.vignetteCentreX;
  65815. },
  65816. /**
  65817. * Sets Vignette centre X Offset.
  65818. */
  65819. set: function (value) {
  65820. this.imageProcessingConfiguration.vignetteCentreX = value;
  65821. },
  65822. enumerable: true,
  65823. configurable: true
  65824. });
  65825. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  65826. /**
  65827. * Gets Vignette centre Y Offset.
  65828. */
  65829. get: function () {
  65830. return this.imageProcessingConfiguration.vignetteCentreY;
  65831. },
  65832. /**
  65833. * Sets Vignette centre Y Offset.
  65834. */
  65835. set: function (value) {
  65836. this.imageProcessingConfiguration.vignetteCentreY = value;
  65837. },
  65838. enumerable: true,
  65839. configurable: true
  65840. });
  65841. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  65842. /**
  65843. * Gets Vignette weight or intensity of the vignette effect.
  65844. */
  65845. get: function () {
  65846. return this.imageProcessingConfiguration.vignetteWeight;
  65847. },
  65848. /**
  65849. * Sets Vignette weight or intensity of the vignette effect.
  65850. */
  65851. set: function (value) {
  65852. this.imageProcessingConfiguration.vignetteWeight = value;
  65853. },
  65854. enumerable: true,
  65855. configurable: true
  65856. });
  65857. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  65858. /**
  65859. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65860. * if vignetteEnabled is set to true.
  65861. */
  65862. get: function () {
  65863. return this.imageProcessingConfiguration.vignetteColor;
  65864. },
  65865. /**
  65866. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65867. * if vignetteEnabled is set to true.
  65868. */
  65869. set: function (value) {
  65870. this.imageProcessingConfiguration.vignetteColor = value;
  65871. },
  65872. enumerable: true,
  65873. configurable: true
  65874. });
  65875. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  65876. /**
  65877. * Gets Camera field of view used by the Vignette effect.
  65878. */
  65879. get: function () {
  65880. return this.imageProcessingConfiguration.vignetteCameraFov;
  65881. },
  65882. /**
  65883. * Sets Camera field of view used by the Vignette effect.
  65884. */
  65885. set: function (value) {
  65886. this.imageProcessingConfiguration.vignetteCameraFov = value;
  65887. },
  65888. enumerable: true,
  65889. configurable: true
  65890. });
  65891. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  65892. /**
  65893. * Gets the vignette blend mode allowing different kind of effect.
  65894. */
  65895. get: function () {
  65896. return this.imageProcessingConfiguration.vignetteBlendMode;
  65897. },
  65898. /**
  65899. * Sets the vignette blend mode allowing different kind of effect.
  65900. */
  65901. set: function (value) {
  65902. this.imageProcessingConfiguration.vignetteBlendMode = value;
  65903. },
  65904. enumerable: true,
  65905. configurable: true
  65906. });
  65907. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  65908. /**
  65909. * Gets wether the vignette effect is enabled.
  65910. */
  65911. get: function () {
  65912. return this.imageProcessingConfiguration.vignetteEnabled;
  65913. },
  65914. /**
  65915. * Sets wether the vignette effect is enabled.
  65916. */
  65917. set: function (value) {
  65918. this.imageProcessingConfiguration.vignetteEnabled = value;
  65919. },
  65920. enumerable: true,
  65921. configurable: true
  65922. });
  65923. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  65924. /**
  65925. * Gets wether the input of the processing is in Gamma or Linear Space.
  65926. */
  65927. get: function () {
  65928. return this._fromLinearSpace;
  65929. },
  65930. /**
  65931. * Sets wether the input of the processing is in Gamma or Linear Space.
  65932. */
  65933. set: function (value) {
  65934. if (this._fromLinearSpace === value) {
  65935. return;
  65936. }
  65937. this._fromLinearSpace = value;
  65938. this._updateParameters();
  65939. },
  65940. enumerable: true,
  65941. configurable: true
  65942. });
  65943. ImageProcessingPostProcess.prototype.getClassName = function () {
  65944. return "ImageProcessingPostProcess";
  65945. };
  65946. ImageProcessingPostProcess.prototype._updateParameters = function () {
  65947. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  65948. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  65949. var defines = "";
  65950. for (var define in this._defines) {
  65951. if (this._defines[define]) {
  65952. defines += "#define " + define + ";\r\n";
  65953. }
  65954. }
  65955. var samplers = ["textureSampler"];
  65956. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  65957. var uniforms = ["scale"];
  65958. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  65959. this.updateEffect(defines, uniforms, samplers);
  65960. };
  65961. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  65962. _super.prototype.dispose.call(this, camera);
  65963. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65964. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65965. }
  65966. this.imageProcessingConfiguration.applyByPostProcess = false;
  65967. };
  65968. __decorate([
  65969. BABYLON.serialize()
  65970. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  65971. return ImageProcessingPostProcess;
  65972. }(BABYLON.PostProcess));
  65973. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  65974. })(BABYLON || (BABYLON = {}));
  65975. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  65976. var BABYLON;
  65977. (function (BABYLON) {
  65978. var BlurPostProcess = /** @class */ (function (_super) {
  65979. __extends(BlurPostProcess, _super);
  65980. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  65981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65982. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65983. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  65984. _this.direction = direction;
  65985. _this._packedFloat = false;
  65986. _this._staticDefines = "";
  65987. _this.onApplyObservable.add(function (effect) {
  65988. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  65989. });
  65990. _this.kernel = kernel;
  65991. return _this;
  65992. }
  65993. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  65994. /**
  65995. * Gets the length in pixels of the blur sample region
  65996. */
  65997. get: function () {
  65998. return this._idealKernel;
  65999. },
  66000. /**
  66001. * Sets the length in pixels of the blur sample region
  66002. */
  66003. set: function (v) {
  66004. if (this._idealKernel === v) {
  66005. return;
  66006. }
  66007. v = Math.max(v, 1);
  66008. this._idealKernel = v;
  66009. this._kernel = this._nearestBestKernel(v);
  66010. this._updateParameters();
  66011. },
  66012. enumerable: true,
  66013. configurable: true
  66014. });
  66015. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  66016. /**
  66017. * Gets wether or not the blur is unpacking/repacking floats
  66018. */
  66019. get: function () {
  66020. return this._packedFloat;
  66021. },
  66022. /**
  66023. * Sets wether or not the blur needs to unpack/repack floats
  66024. */
  66025. set: function (v) {
  66026. if (this._packedFloat === v) {
  66027. return;
  66028. }
  66029. this._packedFloat = v;
  66030. this._updateParameters();
  66031. },
  66032. enumerable: true,
  66033. configurable: true
  66034. });
  66035. BlurPostProcess.prototype._updateParameters = function () {
  66036. // Generate sampling offsets and weights
  66037. var N = this._kernel;
  66038. var centerIndex = (N - 1) / 2;
  66039. // Generate Gaussian sampling weights over kernel
  66040. var offsets = [];
  66041. var weights = [];
  66042. var totalWeight = 0;
  66043. for (var i = 0; i < N; i++) {
  66044. var u = i / (N - 1);
  66045. var w = this._gaussianWeight(u * 2.0 - 1);
  66046. offsets[i] = (i - centerIndex);
  66047. weights[i] = w;
  66048. totalWeight += w;
  66049. }
  66050. // Normalize weights
  66051. for (var i = 0; i < weights.length; i++) {
  66052. weights[i] /= totalWeight;
  66053. }
  66054. // Optimize: combine samples to take advantage of hardware linear sampling
  66055. // Walk from left to center, combining pairs (symmetrically)
  66056. var linearSamplingWeights = [];
  66057. var linearSamplingOffsets = [];
  66058. var linearSamplingMap = [];
  66059. for (var i = 0; i <= centerIndex; i += 2) {
  66060. var j = Math.min(i + 1, Math.floor(centerIndex));
  66061. var singleCenterSample = i === j;
  66062. if (singleCenterSample) {
  66063. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66064. }
  66065. else {
  66066. var sharedCell = j === centerIndex;
  66067. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  66068. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  66069. if (offsetLinear === 0) {
  66070. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  66071. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  66072. }
  66073. else {
  66074. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  66075. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  66076. }
  66077. }
  66078. }
  66079. for (var i = 0; i < linearSamplingMap.length; i++) {
  66080. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  66081. linearSamplingWeights[i] = linearSamplingMap[i].w;
  66082. }
  66083. // Replace with optimized
  66084. offsets = linearSamplingOffsets;
  66085. weights = linearSamplingWeights;
  66086. // Generate shaders
  66087. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  66088. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  66089. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  66090. var defines = "";
  66091. defines += this._staticDefines;
  66092. for (var i = 0; i < varyingCount; i++) {
  66093. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  66094. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  66095. }
  66096. var depCount = 0;
  66097. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  66098. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  66099. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  66100. depCount++;
  66101. }
  66102. if (this.packedFloat) {
  66103. defines += "#define PACKEDFLOAT 1";
  66104. }
  66105. this.updateEffect(defines, null, null, {
  66106. varyingCount: varyingCount,
  66107. depCount: depCount
  66108. });
  66109. };
  66110. /**
  66111. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  66112. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  66113. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  66114. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  66115. * The gaps between physical kernels are compensated for in the weighting of the samples
  66116. * @param idealKernel Ideal blur kernel.
  66117. * @return Nearest best kernel.
  66118. */
  66119. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  66120. var v = Math.round(idealKernel);
  66121. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  66122. var k = _a[_i];
  66123. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  66124. return Math.max(k, 3);
  66125. }
  66126. }
  66127. return Math.max(v, 3);
  66128. };
  66129. /**
  66130. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  66131. * @param x The point on the Gaussian distribution to sample.
  66132. * @return the value of the Gaussian function at x.
  66133. */
  66134. BlurPostProcess.prototype._gaussianWeight = function (x) {
  66135. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  66136. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  66137. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  66138. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  66139. // truncated at around 1.3% of peak strength.
  66140. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  66141. var sigma = (1 / 3);
  66142. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  66143. var exponent = -((x * x) / (2.0 * sigma * sigma));
  66144. var weight = (1.0 / denominator) * Math.exp(exponent);
  66145. return weight;
  66146. };
  66147. /**
  66148. * Generates a string that can be used as a floating point number in GLSL.
  66149. * @param x Value to print.
  66150. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  66151. * @return GLSL float string.
  66152. */
  66153. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  66154. if (decimalFigures === void 0) { decimalFigures = 8; }
  66155. return x.toFixed(decimalFigures).replace(/0+$/, '');
  66156. };
  66157. return BlurPostProcess;
  66158. }(BABYLON.PostProcess));
  66159. BABYLON.BlurPostProcess = BlurPostProcess;
  66160. })(BABYLON || (BABYLON = {}));
  66161. //# sourceMappingURL=babylon.blurPostProcess.js.map
  66162. var BABYLON;
  66163. (function (BABYLON) {
  66164. var Bone = /** @class */ (function (_super) {
  66165. __extends(Bone, _super);
  66166. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  66167. if (parentBone === void 0) { parentBone = null; }
  66168. if (localMatrix === void 0) { localMatrix = null; }
  66169. if (restPose === void 0) { restPose = null; }
  66170. if (baseMatrix === void 0) { baseMatrix = null; }
  66171. if (index === void 0) { index = null; }
  66172. var _this = _super.call(this, name, skeleton.getScene()) || this;
  66173. _this.name = name;
  66174. _this.children = new Array();
  66175. _this.animations = new Array();
  66176. // Set this value to map this bone to a different index in the transform matrices.
  66177. // Set this value to -1 to exclude the bone from the transform matrices.
  66178. _this._index = null;
  66179. _this._worldTransform = new BABYLON.Matrix();
  66180. _this._absoluteTransform = new BABYLON.Matrix();
  66181. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  66182. _this._scaleMatrix = BABYLON.Matrix.Identity();
  66183. _this._scaleVector = BABYLON.Vector3.One();
  66184. _this._negateScaleChildren = BABYLON.Vector3.One();
  66185. _this._scalingDeterminant = 1;
  66186. _this._skeleton = skeleton;
  66187. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  66188. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  66189. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  66190. _this._index = index;
  66191. skeleton.bones.push(_this);
  66192. _this.setParent(parentBone, false);
  66193. _this._updateDifferenceMatrix();
  66194. return _this;
  66195. }
  66196. Object.defineProperty(Bone.prototype, "_matrix", {
  66197. get: function () {
  66198. return this._localMatrix;
  66199. },
  66200. set: function (val) {
  66201. if (this._localMatrix) {
  66202. this._localMatrix.copyFrom(val);
  66203. }
  66204. else {
  66205. this._localMatrix = val;
  66206. }
  66207. },
  66208. enumerable: true,
  66209. configurable: true
  66210. });
  66211. // Members
  66212. Bone.prototype.getSkeleton = function () {
  66213. return this._skeleton;
  66214. };
  66215. Bone.prototype.getParent = function () {
  66216. return this._parent;
  66217. };
  66218. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  66219. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66220. if (this._parent === parent) {
  66221. return;
  66222. }
  66223. if (this._parent) {
  66224. var index = this._parent.children.indexOf(this);
  66225. if (index !== -1) {
  66226. this._parent.children.splice(index, 1);
  66227. }
  66228. }
  66229. this._parent = parent;
  66230. if (this._parent) {
  66231. this._parent.children.push(this);
  66232. }
  66233. if (updateDifferenceMatrix) {
  66234. this._updateDifferenceMatrix();
  66235. }
  66236. };
  66237. Bone.prototype.getLocalMatrix = function () {
  66238. return this._localMatrix;
  66239. };
  66240. Bone.prototype.getBaseMatrix = function () {
  66241. return this._baseMatrix;
  66242. };
  66243. Bone.prototype.getRestPose = function () {
  66244. return this._restPose;
  66245. };
  66246. Bone.prototype.returnToRest = function () {
  66247. this.updateMatrix(this._restPose.clone());
  66248. };
  66249. Bone.prototype.getWorldMatrix = function () {
  66250. return this._worldTransform;
  66251. };
  66252. Bone.prototype.getInvertedAbsoluteTransform = function () {
  66253. return this._invertedAbsoluteTransform;
  66254. };
  66255. Bone.prototype.getAbsoluteTransform = function () {
  66256. return this._absoluteTransform;
  66257. };
  66258. Object.defineProperty(Bone.prototype, "position", {
  66259. // Properties (matches AbstractMesh properties)
  66260. get: function () {
  66261. return this.getPosition();
  66262. },
  66263. set: function (newPosition) {
  66264. this.setPosition(newPosition);
  66265. },
  66266. enumerable: true,
  66267. configurable: true
  66268. });
  66269. Object.defineProperty(Bone.prototype, "rotation", {
  66270. get: function () {
  66271. return this.getRotation();
  66272. },
  66273. set: function (newRotation) {
  66274. this.setRotation(newRotation);
  66275. },
  66276. enumerable: true,
  66277. configurable: true
  66278. });
  66279. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  66280. get: function () {
  66281. return this.getRotationQuaternion();
  66282. },
  66283. set: function (newRotation) {
  66284. this.setRotationQuaternion(newRotation);
  66285. },
  66286. enumerable: true,
  66287. configurable: true
  66288. });
  66289. Object.defineProperty(Bone.prototype, "scaling", {
  66290. get: function () {
  66291. return this.getScale();
  66292. },
  66293. set: function (newScaling) {
  66294. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  66295. },
  66296. enumerable: true,
  66297. configurable: true
  66298. });
  66299. // Methods
  66300. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  66301. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  66302. this._baseMatrix = matrix.clone();
  66303. this._localMatrix = matrix.clone();
  66304. this._skeleton._markAsDirty();
  66305. if (updateDifferenceMatrix) {
  66306. this._updateDifferenceMatrix();
  66307. }
  66308. };
  66309. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  66310. if (!rootMatrix) {
  66311. rootMatrix = this._baseMatrix;
  66312. }
  66313. if (this._parent) {
  66314. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66315. }
  66316. else {
  66317. this._absoluteTransform.copyFrom(rootMatrix);
  66318. }
  66319. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  66320. for (var index = 0; index < this.children.length; index++) {
  66321. this.children[index]._updateDifferenceMatrix();
  66322. }
  66323. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  66324. };
  66325. Bone.prototype.markAsDirty = function () {
  66326. this._currentRenderId++;
  66327. this._skeleton._markAsDirty();
  66328. };
  66329. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  66330. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66331. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  66332. // all animation may be coming from a library skeleton, so may need to create animation
  66333. if (this.animations.length === 0) {
  66334. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  66335. this.animations[0].setKeys([]);
  66336. }
  66337. // get animation info / verify there is such a range from the source bone
  66338. var sourceRange = source.animations[0].getRange(rangeName);
  66339. if (!sourceRange) {
  66340. return false;
  66341. }
  66342. var from = sourceRange.from;
  66343. var to = sourceRange.to;
  66344. var sourceKeys = source.animations[0].getKeys();
  66345. // rescaling prep
  66346. var sourceBoneLength = source.length;
  66347. var sourceParent = source.getParent();
  66348. var parent = this.getParent();
  66349. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  66350. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  66351. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  66352. var destKeys = this.animations[0].getKeys();
  66353. // loop vars declaration
  66354. var orig;
  66355. var origTranslation;
  66356. var mat;
  66357. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  66358. orig = sourceKeys[key];
  66359. if (orig.frame >= from && orig.frame <= to) {
  66360. if (rescaleAsRequired) {
  66361. mat = orig.value.clone();
  66362. // scale based on parent ratio, when bone has parent
  66363. if (parentScalingReqd) {
  66364. origTranslation = mat.getTranslation();
  66365. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  66366. // scale based on skeleton dimension ratio when root bone, and value is passed
  66367. }
  66368. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  66369. origTranslation = mat.getTranslation();
  66370. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  66371. // use original when root bone, and no data for skelDimensionsRatio
  66372. }
  66373. else {
  66374. mat = orig.value;
  66375. }
  66376. }
  66377. else {
  66378. mat = orig.value;
  66379. }
  66380. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  66381. }
  66382. }
  66383. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  66384. return true;
  66385. };
  66386. /**
  66387. * Translate the bone in local or world space.
  66388. * @param vec The amount to translate the bone.
  66389. * @param space The space that the translation is in.
  66390. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66391. */
  66392. Bone.prototype.translate = function (vec, space, mesh) {
  66393. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66394. var lm = this.getLocalMatrix();
  66395. if (space == BABYLON.Space.LOCAL) {
  66396. lm.m[12] += vec.x;
  66397. lm.m[13] += vec.y;
  66398. lm.m[14] += vec.z;
  66399. }
  66400. else {
  66401. var wm = null;
  66402. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66403. if (mesh) {
  66404. wm = mesh.getWorldMatrix();
  66405. }
  66406. this._skeleton.computeAbsoluteTransforms();
  66407. var tmat = Bone._tmpMats[0];
  66408. var tvec = Bone._tmpVecs[0];
  66409. if (this._parent) {
  66410. if (mesh && wm) {
  66411. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66412. tmat.multiplyToRef(wm, tmat);
  66413. }
  66414. else {
  66415. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66416. }
  66417. }
  66418. tmat.m[12] = 0;
  66419. tmat.m[13] = 0;
  66420. tmat.m[14] = 0;
  66421. tmat.invert();
  66422. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  66423. lm.m[12] += tvec.x;
  66424. lm.m[13] += tvec.y;
  66425. lm.m[14] += tvec.z;
  66426. }
  66427. this.markAsDirty();
  66428. };
  66429. /**
  66430. * Set the postion of the bone in local or world space.
  66431. * @param position The position to set the bone.
  66432. * @param space The space that the position is in.
  66433. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66434. */
  66435. Bone.prototype.setPosition = function (position, space, mesh) {
  66436. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66437. var lm = this.getLocalMatrix();
  66438. if (space == BABYLON.Space.LOCAL) {
  66439. lm.m[12] = position.x;
  66440. lm.m[13] = position.y;
  66441. lm.m[14] = position.z;
  66442. }
  66443. else {
  66444. var wm = null;
  66445. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66446. if (mesh) {
  66447. wm = mesh.getWorldMatrix();
  66448. }
  66449. this._skeleton.computeAbsoluteTransforms();
  66450. var tmat = Bone._tmpMats[0];
  66451. var vec = Bone._tmpVecs[0];
  66452. if (this._parent) {
  66453. if (mesh && wm) {
  66454. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66455. tmat.multiplyToRef(wm, tmat);
  66456. }
  66457. else {
  66458. tmat.copyFrom(this._parent.getAbsoluteTransform());
  66459. }
  66460. }
  66461. tmat.invert();
  66462. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  66463. lm.m[12] = vec.x;
  66464. lm.m[13] = vec.y;
  66465. lm.m[14] = vec.z;
  66466. }
  66467. this.markAsDirty();
  66468. };
  66469. /**
  66470. * Set the absolute postion of the bone (world space).
  66471. * @param position The position to set the bone.
  66472. * @param mesh The mesh that this bone is attached to.
  66473. */
  66474. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  66475. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  66476. };
  66477. /**
  66478. * Set the scale of the bone on the x, y and z axes.
  66479. * @param x The scale of the bone on the x axis.
  66480. * @param x The scale of the bone on the y axis.
  66481. * @param z The scale of the bone on the z axis.
  66482. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66483. */
  66484. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  66485. if (scaleChildren === void 0) { scaleChildren = false; }
  66486. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  66487. if (!scaleChildren) {
  66488. this._negateScaleChildren.x = 1 / x;
  66489. this._negateScaleChildren.y = 1 / y;
  66490. this._negateScaleChildren.z = 1 / z;
  66491. }
  66492. this._syncScaleVector();
  66493. }
  66494. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  66495. };
  66496. /**
  66497. * Scale the bone on the x, y and z axes.
  66498. * @param x The amount to scale the bone on the x axis.
  66499. * @param x The amount to scale the bone on the y axis.
  66500. * @param z The amount to scale the bone on the z axis.
  66501. * @param scaleChildren Set this to true if children of the bone should be scaled.
  66502. */
  66503. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  66504. if (scaleChildren === void 0) { scaleChildren = false; }
  66505. var locMat = this.getLocalMatrix();
  66506. var origLocMat = Bone._tmpMats[0];
  66507. origLocMat.copyFrom(locMat);
  66508. var origLocMatInv = Bone._tmpMats[1];
  66509. origLocMatInv.copyFrom(origLocMat);
  66510. origLocMatInv.invert();
  66511. var scaleMat = Bone._tmpMats[2];
  66512. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  66513. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  66514. this._scaleVector.x *= x;
  66515. this._scaleVector.y *= y;
  66516. this._scaleVector.z *= z;
  66517. locMat.multiplyToRef(origLocMatInv, locMat);
  66518. locMat.multiplyToRef(scaleMat, locMat);
  66519. locMat.multiplyToRef(origLocMat, locMat);
  66520. var parent = this.getParent();
  66521. if (parent) {
  66522. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  66523. }
  66524. else {
  66525. this.getAbsoluteTransform().copyFrom(locMat);
  66526. }
  66527. var len = this.children.length;
  66528. scaleMat.invert();
  66529. for (var i = 0; i < len; i++) {
  66530. var child = this.children[i];
  66531. var cm = child.getLocalMatrix();
  66532. cm.multiplyToRef(scaleMat, cm);
  66533. var lm = child.getLocalMatrix();
  66534. lm.m[12] *= x;
  66535. lm.m[13] *= y;
  66536. lm.m[14] *= z;
  66537. }
  66538. this.computeAbsoluteTransforms();
  66539. if (scaleChildren) {
  66540. for (var i = 0; i < len; i++) {
  66541. this.children[i].scale(x, y, z, scaleChildren);
  66542. }
  66543. }
  66544. this.markAsDirty();
  66545. };
  66546. /**
  66547. * Set the yaw, pitch, and roll of the bone in local or world space.
  66548. * @param yaw The rotation of the bone on the y axis.
  66549. * @param pitch The rotation of the bone on the x axis.
  66550. * @param roll The rotation of the bone on the z axis.
  66551. * @param space The space that the axes of rotation are in.
  66552. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66553. */
  66554. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  66555. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66556. var rotMat = Bone._tmpMats[0];
  66557. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  66558. var rotMatInv = Bone._tmpMats[1];
  66559. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66560. rotMatInv.multiplyToRef(rotMat, rotMat);
  66561. this._rotateWithMatrix(rotMat, space, mesh);
  66562. };
  66563. /**
  66564. * Rotate the bone on an axis in local or world space.
  66565. * @param axis The axis to rotate the bone on.
  66566. * @param amount The amount to rotate the bone.
  66567. * @param space The space that the axis is in.
  66568. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66569. */
  66570. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  66571. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66572. var rmat = Bone._tmpMats[0];
  66573. rmat.m[12] = 0;
  66574. rmat.m[13] = 0;
  66575. rmat.m[14] = 0;
  66576. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  66577. this._rotateWithMatrix(rmat, space, mesh);
  66578. };
  66579. /**
  66580. * Set the rotation of the bone to a particular axis angle in local or world space.
  66581. * @param axis The axis to rotate the bone on.
  66582. * @param angle The angle that the bone should be rotated to.
  66583. * @param space The space that the axis is in.
  66584. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66585. */
  66586. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  66587. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66588. var rotMat = Bone._tmpMats[0];
  66589. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  66590. var rotMatInv = Bone._tmpMats[1];
  66591. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66592. rotMatInv.multiplyToRef(rotMat, rotMat);
  66593. this._rotateWithMatrix(rotMat, space, mesh);
  66594. };
  66595. /**
  66596. * Set the euler rotation of the bone in local of world space.
  66597. * @param rotation The euler rotation that the bone should be set to.
  66598. * @param space The space that the rotation is in.
  66599. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66600. */
  66601. Bone.prototype.setRotation = function (rotation, space, mesh) {
  66602. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66603. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  66604. };
  66605. /**
  66606. * Set the quaternion rotation of the bone in local of world space.
  66607. * @param quat The quaternion rotation that the bone should be set to.
  66608. * @param space The space that the rotation is in.
  66609. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66610. */
  66611. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  66612. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66613. var rotMatInv = Bone._tmpMats[0];
  66614. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66615. var rotMat = Bone._tmpMats[1];
  66616. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  66617. rotMatInv.multiplyToRef(rotMat, rotMat);
  66618. this._rotateWithMatrix(rotMat, space, mesh);
  66619. };
  66620. /**
  66621. * Set the rotation matrix of the bone in local of world space.
  66622. * @param rotMat The rotation matrix that the bone should be set to.
  66623. * @param space The space that the rotation is in.
  66624. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66625. */
  66626. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  66627. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66628. var rotMatInv = Bone._tmpMats[0];
  66629. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66630. var rotMat2 = Bone._tmpMats[1];
  66631. rotMat2.copyFrom(rotMat);
  66632. rotMatInv.multiplyToRef(rotMat, rotMat2);
  66633. this._rotateWithMatrix(rotMat2, space, mesh);
  66634. };
  66635. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  66636. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66637. var lmat = this.getLocalMatrix();
  66638. var lx = lmat.m[12];
  66639. var ly = lmat.m[13];
  66640. var lz = lmat.m[14];
  66641. var parent = this.getParent();
  66642. var parentScale = Bone._tmpMats[3];
  66643. var parentScaleInv = Bone._tmpMats[4];
  66644. if (parent) {
  66645. if (space == BABYLON.Space.WORLD) {
  66646. if (mesh) {
  66647. parentScale.copyFrom(mesh.getWorldMatrix());
  66648. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  66649. }
  66650. else {
  66651. parentScale.copyFrom(parent.getAbsoluteTransform());
  66652. }
  66653. }
  66654. else {
  66655. parentScale = parent._scaleMatrix;
  66656. }
  66657. parentScaleInv.copyFrom(parentScale);
  66658. parentScaleInv.invert();
  66659. lmat.multiplyToRef(parentScale, lmat);
  66660. lmat.multiplyToRef(rmat, lmat);
  66661. lmat.multiplyToRef(parentScaleInv, lmat);
  66662. }
  66663. else {
  66664. if (space == BABYLON.Space.WORLD && mesh) {
  66665. parentScale.copyFrom(mesh.getWorldMatrix());
  66666. parentScaleInv.copyFrom(parentScale);
  66667. parentScaleInv.invert();
  66668. lmat.multiplyToRef(parentScale, lmat);
  66669. lmat.multiplyToRef(rmat, lmat);
  66670. lmat.multiplyToRef(parentScaleInv, lmat);
  66671. }
  66672. else {
  66673. lmat.multiplyToRef(rmat, lmat);
  66674. }
  66675. }
  66676. lmat.m[12] = lx;
  66677. lmat.m[13] = ly;
  66678. lmat.m[14] = lz;
  66679. this.computeAbsoluteTransforms();
  66680. this.markAsDirty();
  66681. };
  66682. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  66683. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66684. if (space == BABYLON.Space.WORLD) {
  66685. var scaleMatrix = Bone._tmpMats[2];
  66686. scaleMatrix.copyFrom(this._scaleMatrix);
  66687. rotMatInv.copyFrom(this.getAbsoluteTransform());
  66688. if (mesh) {
  66689. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  66690. var meshScale = Bone._tmpMats[3];
  66691. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  66692. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  66693. }
  66694. rotMatInv.invert();
  66695. scaleMatrix.m[0] *= this._scalingDeterminant;
  66696. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66697. }
  66698. else {
  66699. rotMatInv.copyFrom(this.getLocalMatrix());
  66700. rotMatInv.invert();
  66701. var scaleMatrix = Bone._tmpMats[2];
  66702. scaleMatrix.copyFrom(this._scaleMatrix);
  66703. if (this._parent) {
  66704. var pscaleMatrix = Bone._tmpMats[3];
  66705. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  66706. pscaleMatrix.invert();
  66707. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  66708. }
  66709. else {
  66710. scaleMatrix.m[0] *= this._scalingDeterminant;
  66711. }
  66712. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66713. }
  66714. };
  66715. /**
  66716. * Get the scale of the bone
  66717. * @returns the scale of the bone
  66718. */
  66719. Bone.prototype.getScale = function () {
  66720. return this._scaleVector.clone();
  66721. };
  66722. /**
  66723. * Copy the scale of the bone to a vector3.
  66724. * @param result The vector3 to copy the scale to
  66725. */
  66726. Bone.prototype.getScaleToRef = function (result) {
  66727. result.copyFrom(this._scaleVector);
  66728. };
  66729. /**
  66730. * Get the position of the bone in local or world space.
  66731. * @param space The space that the returned position is in.
  66732. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66733. * @returns The position of the bone
  66734. */
  66735. Bone.prototype.getPosition = function (space, mesh) {
  66736. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66737. if (mesh === void 0) { mesh = null; }
  66738. var pos = BABYLON.Vector3.Zero();
  66739. this.getPositionToRef(space, mesh, pos);
  66740. return pos;
  66741. };
  66742. /**
  66743. * Copy the position of the bone to a vector3 in local or world space.
  66744. * @param space The space that the returned position is in.
  66745. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66746. * @param result The vector3 to copy the position to.
  66747. */
  66748. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  66749. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66750. if (space == BABYLON.Space.LOCAL) {
  66751. var lm = this.getLocalMatrix();
  66752. result.x = lm.m[12];
  66753. result.y = lm.m[13];
  66754. result.z = lm.m[14];
  66755. }
  66756. else {
  66757. var wm = null;
  66758. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66759. if (mesh) {
  66760. wm = mesh.getWorldMatrix();
  66761. }
  66762. this._skeleton.computeAbsoluteTransforms();
  66763. var tmat = Bone._tmpMats[0];
  66764. if (mesh && wm) {
  66765. tmat.copyFrom(this.getAbsoluteTransform());
  66766. tmat.multiplyToRef(wm, tmat);
  66767. }
  66768. else {
  66769. tmat = this.getAbsoluteTransform();
  66770. }
  66771. result.x = tmat.m[12];
  66772. result.y = tmat.m[13];
  66773. result.z = tmat.m[14];
  66774. }
  66775. };
  66776. /**
  66777. * Get the absolute position of the bone (world space).
  66778. * @param mesh The mesh that this bone is attached to.
  66779. * @returns The absolute position of the bone
  66780. */
  66781. Bone.prototype.getAbsolutePosition = function (mesh) {
  66782. if (mesh === void 0) { mesh = null; }
  66783. var pos = BABYLON.Vector3.Zero();
  66784. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  66785. return pos;
  66786. };
  66787. /**
  66788. * Copy the absolute position of the bone (world space) to the result param.
  66789. * @param mesh The mesh that this bone is attached to.
  66790. * @param result The vector3 to copy the absolute position to.
  66791. */
  66792. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  66793. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  66794. };
  66795. /**
  66796. * Compute the absolute transforms of this bone and its children.
  66797. */
  66798. Bone.prototype.computeAbsoluteTransforms = function () {
  66799. if (this._parent) {
  66800. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66801. }
  66802. else {
  66803. this._absoluteTransform.copyFrom(this._localMatrix);
  66804. var poseMatrix = this._skeleton.getPoseMatrix();
  66805. if (poseMatrix) {
  66806. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  66807. }
  66808. }
  66809. var children = this.children;
  66810. var len = children.length;
  66811. for (var i = 0; i < len; i++) {
  66812. children[i].computeAbsoluteTransforms();
  66813. }
  66814. };
  66815. Bone.prototype._syncScaleVector = function () {
  66816. var lm = this.getLocalMatrix();
  66817. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  66818. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  66819. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  66820. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  66821. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  66822. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  66823. this._scaleVector.x = xs * Math.sqrt(xsq);
  66824. this._scaleVector.y = ys * Math.sqrt(ysq);
  66825. this._scaleVector.z = zs * Math.sqrt(zsq);
  66826. if (this._parent) {
  66827. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  66828. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  66829. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  66830. }
  66831. 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);
  66832. };
  66833. /**
  66834. * Get the world direction from an axis that is in the local space of the bone.
  66835. * @param localAxis The local direction that is used to compute the world direction.
  66836. * @param mesh The mesh that this bone is attached to.
  66837. * @returns The world direction
  66838. */
  66839. Bone.prototype.getDirection = function (localAxis, mesh) {
  66840. if (mesh === void 0) { mesh = null; }
  66841. var result = BABYLON.Vector3.Zero();
  66842. this.getDirectionToRef(localAxis, mesh, result);
  66843. return result;
  66844. };
  66845. /**
  66846. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  66847. * @param localAxis The local direction that is used to compute the world direction.
  66848. * @param mesh The mesh that this bone is attached to.
  66849. * @param result The vector3 that the world direction will be copied to.
  66850. */
  66851. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  66852. if (mesh === void 0) { mesh = null; }
  66853. var wm = null;
  66854. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66855. if (mesh) {
  66856. wm = mesh.getWorldMatrix();
  66857. }
  66858. this._skeleton.computeAbsoluteTransforms();
  66859. var mat = Bone._tmpMats[0];
  66860. mat.copyFrom(this.getAbsoluteTransform());
  66861. if (mesh && wm) {
  66862. mat.multiplyToRef(wm, mat);
  66863. }
  66864. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  66865. result.normalize();
  66866. };
  66867. /**
  66868. * Get the euler rotation of the bone in local or world space.
  66869. * @param space The space that the rotation should be in.
  66870. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66871. * @returns The euler rotation
  66872. */
  66873. Bone.prototype.getRotation = function (space, mesh) {
  66874. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66875. if (mesh === void 0) { mesh = null; }
  66876. var result = BABYLON.Vector3.Zero();
  66877. this.getRotationToRef(space, mesh, result);
  66878. return result;
  66879. };
  66880. /**
  66881. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  66882. * @param space The space that the rotation should be in.
  66883. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66884. * @param result The vector3 that the rotation should be copied to.
  66885. */
  66886. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  66887. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66888. if (mesh === void 0) { mesh = null; }
  66889. var quat = Bone._tmpQuat;
  66890. this.getRotationQuaternionToRef(space, mesh, quat);
  66891. quat.toEulerAnglesToRef(result);
  66892. };
  66893. /**
  66894. * Get the quaternion rotation of the bone in either local or world space.
  66895. * @param space The space that the rotation should be in.
  66896. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66897. * @returns The quaternion rotation
  66898. */
  66899. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  66900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66901. if (mesh === void 0) { mesh = null; }
  66902. var result = BABYLON.Quaternion.Identity();
  66903. this.getRotationQuaternionToRef(space, mesh, result);
  66904. return result;
  66905. };
  66906. /**
  66907. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  66908. * @param space The space that the rotation should be in.
  66909. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66910. * @param result The quaternion that the rotation should be copied to.
  66911. */
  66912. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  66913. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66914. if (mesh === void 0) { mesh = null; }
  66915. if (space == BABYLON.Space.LOCAL) {
  66916. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66917. }
  66918. else {
  66919. var mat = Bone._tmpMats[0];
  66920. var amat = this.getAbsoluteTransform();
  66921. if (mesh) {
  66922. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66923. }
  66924. else {
  66925. mat.copyFrom(amat);
  66926. }
  66927. mat.m[0] *= this._scalingDeterminant;
  66928. mat.m[1] *= this._scalingDeterminant;
  66929. mat.m[2] *= this._scalingDeterminant;
  66930. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66931. }
  66932. };
  66933. /**
  66934. * Get the rotation matrix of the bone in local or world space.
  66935. * @param space The space that the rotation should be in.
  66936. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66937. * @returns The rotation matrix
  66938. */
  66939. Bone.prototype.getRotationMatrix = function (space, mesh) {
  66940. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66941. var result = BABYLON.Matrix.Identity();
  66942. this.getRotationMatrixToRef(space, mesh, result);
  66943. return result;
  66944. };
  66945. /**
  66946. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  66947. * @param space The space that the rotation should be in.
  66948. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66949. * @param result The quaternion that the rotation should be copied to.
  66950. */
  66951. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  66952. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66953. if (space == BABYLON.Space.LOCAL) {
  66954. this.getLocalMatrix().getRotationMatrixToRef(result);
  66955. }
  66956. else {
  66957. var mat = Bone._tmpMats[0];
  66958. var amat = this.getAbsoluteTransform();
  66959. if (mesh) {
  66960. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66961. }
  66962. else {
  66963. mat.copyFrom(amat);
  66964. }
  66965. mat.m[0] *= this._scalingDeterminant;
  66966. mat.m[1] *= this._scalingDeterminant;
  66967. mat.m[2] *= this._scalingDeterminant;
  66968. mat.getRotationMatrixToRef(result);
  66969. }
  66970. };
  66971. /**
  66972. * Get the world position of a point that is in the local space of the bone.
  66973. * @param position The local position
  66974. * @param mesh The mesh that this bone is attached to.
  66975. * @returns The world position
  66976. */
  66977. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  66978. if (mesh === void 0) { mesh = null; }
  66979. var result = BABYLON.Vector3.Zero();
  66980. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  66981. return result;
  66982. };
  66983. /**
  66984. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  66985. * @param position The local position
  66986. * @param mesh The mesh that this bone is attached to.
  66987. * @param result The vector3 that the world position should be copied to.
  66988. */
  66989. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  66990. if (mesh === void 0) { mesh = null; }
  66991. var wm = null;
  66992. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66993. if (mesh) {
  66994. wm = mesh.getWorldMatrix();
  66995. }
  66996. this._skeleton.computeAbsoluteTransforms();
  66997. var tmat = Bone._tmpMats[0];
  66998. if (mesh && wm) {
  66999. tmat.copyFrom(this.getAbsoluteTransform());
  67000. tmat.multiplyToRef(wm, tmat);
  67001. }
  67002. else {
  67003. tmat = this.getAbsoluteTransform();
  67004. }
  67005. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67006. };
  67007. /**
  67008. * Get the local position of a point that is in world space.
  67009. * @param position The world position
  67010. * @param mesh The mesh that this bone is attached to.
  67011. * @returns The local position
  67012. */
  67013. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  67014. if (mesh === void 0) { mesh = null; }
  67015. var result = BABYLON.Vector3.Zero();
  67016. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  67017. return result;
  67018. };
  67019. /**
  67020. * Get the local position of a point that is in world space and copy it to the result param.
  67021. * @param position The world position
  67022. * @param mesh The mesh that this bone is attached to.
  67023. * @param result The vector3 that the local position should be copied to.
  67024. */
  67025. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  67026. if (mesh === void 0) { mesh = null; }
  67027. var wm = null;
  67028. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  67029. if (mesh) {
  67030. wm = mesh.getWorldMatrix();
  67031. }
  67032. this._skeleton.computeAbsoluteTransforms();
  67033. var tmat = Bone._tmpMats[0];
  67034. tmat.copyFrom(this.getAbsoluteTransform());
  67035. if (mesh && wm) {
  67036. tmat.multiplyToRef(wm, tmat);
  67037. }
  67038. tmat.invert();
  67039. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  67040. };
  67041. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67042. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  67043. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67044. return Bone;
  67045. }(BABYLON.Node));
  67046. BABYLON.Bone = Bone;
  67047. })(BABYLON || (BABYLON = {}));
  67048. //# sourceMappingURL=babylon.bone.js.map
  67049. var BABYLON;
  67050. (function (BABYLON) {
  67051. var BoneIKController = /** @class */ (function () {
  67052. function BoneIKController(mesh, bone, options) {
  67053. this.targetPosition = BABYLON.Vector3.Zero();
  67054. this.poleTargetPosition = BABYLON.Vector3.Zero();
  67055. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  67056. this.poleAngle = 0;
  67057. this.slerpAmount = 1;
  67058. this._bone1Quat = BABYLON.Quaternion.Identity();
  67059. this._bone1Mat = BABYLON.Matrix.Identity();
  67060. this._bone2Ang = Math.PI;
  67061. this._maxAngle = Math.PI;
  67062. this._rightHandedSystem = false;
  67063. this._bendAxis = BABYLON.Vector3.Right();
  67064. this._slerping = false;
  67065. this._adjustRoll = 0;
  67066. this._bone2 = bone;
  67067. this._bone1 = bone.getParent();
  67068. if (!this._bone1) {
  67069. return;
  67070. }
  67071. this.mesh = mesh;
  67072. var bonePos = bone.getPosition();
  67073. if (bone.getAbsoluteTransform().determinant() > 0) {
  67074. this._rightHandedSystem = true;
  67075. this._bendAxis.x = 0;
  67076. this._bendAxis.y = 0;
  67077. this._bendAxis.z = -1;
  67078. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  67079. this._adjustRoll = Math.PI * .5;
  67080. this._bendAxis.z = 1;
  67081. }
  67082. }
  67083. if (this._bone1.length) {
  67084. var boneScale1 = this._bone1.getScale();
  67085. var boneScale2 = this._bone2.getScale();
  67086. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  67087. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  67088. }
  67089. else if (this._bone1.children[0]) {
  67090. mesh.computeWorldMatrix(true);
  67091. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  67092. var pos2 = this._bone2.getAbsolutePosition(mesh);
  67093. var pos3 = this._bone1.getAbsolutePosition(mesh);
  67094. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  67095. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  67096. }
  67097. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  67098. this.maxAngle = Math.PI;
  67099. if (options) {
  67100. if (options.targetMesh) {
  67101. this.targetMesh = options.targetMesh;
  67102. this.targetMesh.computeWorldMatrix(true);
  67103. }
  67104. if (options.poleTargetMesh) {
  67105. this.poleTargetMesh = options.poleTargetMesh;
  67106. this.poleTargetMesh.computeWorldMatrix(true);
  67107. }
  67108. else if (options.poleTargetBone) {
  67109. this.poleTargetBone = options.poleTargetBone;
  67110. }
  67111. else if (this._bone1.getParent()) {
  67112. this.poleTargetBone = this._bone1.getParent();
  67113. }
  67114. if (options.poleTargetLocalOffset) {
  67115. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  67116. }
  67117. if (options.poleAngle) {
  67118. this.poleAngle = options.poleAngle;
  67119. }
  67120. if (options.bendAxis) {
  67121. this._bendAxis.copyFrom(options.bendAxis);
  67122. }
  67123. if (options.maxAngle) {
  67124. this.maxAngle = options.maxAngle;
  67125. }
  67126. if (options.slerpAmount) {
  67127. this.slerpAmount = options.slerpAmount;
  67128. }
  67129. }
  67130. }
  67131. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  67132. get: function () {
  67133. return this._maxAngle;
  67134. },
  67135. set: function (value) {
  67136. this._setMaxAngle(value);
  67137. },
  67138. enumerable: true,
  67139. configurable: true
  67140. });
  67141. BoneIKController.prototype._setMaxAngle = function (ang) {
  67142. if (ang < 0) {
  67143. ang = 0;
  67144. }
  67145. if (ang > Math.PI || ang == undefined) {
  67146. ang = Math.PI;
  67147. }
  67148. this._maxAngle = ang;
  67149. var a = this._bone1Length;
  67150. var b = this._bone2Length;
  67151. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  67152. };
  67153. BoneIKController.prototype.update = function () {
  67154. var bone1 = this._bone1;
  67155. if (!bone1) {
  67156. return;
  67157. }
  67158. var target = this.targetPosition;
  67159. var poleTarget = this.poleTargetPosition;
  67160. var mat1 = BoneIKController._tmpMats[0];
  67161. var mat2 = BoneIKController._tmpMats[1];
  67162. if (this.targetMesh) {
  67163. target.copyFrom(this.targetMesh.getAbsolutePosition());
  67164. }
  67165. if (this.poleTargetBone) {
  67166. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  67167. }
  67168. else if (this.poleTargetMesh) {
  67169. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  67170. }
  67171. var bonePos = BoneIKController._tmpVecs[0];
  67172. var zaxis = BoneIKController._tmpVecs[1];
  67173. var xaxis = BoneIKController._tmpVecs[2];
  67174. var yaxis = BoneIKController._tmpVecs[3];
  67175. var upAxis = BoneIKController._tmpVecs[4];
  67176. var _tmpQuat = BoneIKController._tmpQuat;
  67177. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  67178. poleTarget.subtractToRef(bonePos, upAxis);
  67179. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  67180. upAxis.y = 1;
  67181. }
  67182. else {
  67183. upAxis.normalize();
  67184. }
  67185. target.subtractToRef(bonePos, yaxis);
  67186. yaxis.normalize();
  67187. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  67188. zaxis.normalize();
  67189. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  67190. xaxis.normalize();
  67191. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  67192. var a = this._bone1Length;
  67193. var b = this._bone2Length;
  67194. var c = BABYLON.Vector3.Distance(bonePos, target);
  67195. if (this._maxReach > 0) {
  67196. c = Math.min(this._maxReach, c);
  67197. }
  67198. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  67199. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  67200. if (acosa > 1) {
  67201. acosa = 1;
  67202. }
  67203. if (acosb > 1) {
  67204. acosb = 1;
  67205. }
  67206. if (acosa < -1) {
  67207. acosa = -1;
  67208. }
  67209. if (acosb < -1) {
  67210. acosb = -1;
  67211. }
  67212. var angA = Math.acos(acosa);
  67213. var angB = Math.acos(acosb);
  67214. var angC = -angA - angB;
  67215. if (this._rightHandedSystem) {
  67216. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  67217. mat2.multiplyToRef(mat1, mat1);
  67218. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  67219. mat2.multiplyToRef(mat1, mat1);
  67220. }
  67221. else {
  67222. var _tmpVec = BoneIKController._tmpVecs[5];
  67223. _tmpVec.copyFrom(this._bendAxis);
  67224. _tmpVec.x *= -1;
  67225. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  67226. mat2.multiplyToRef(mat1, mat1);
  67227. }
  67228. if (this.poleAngle) {
  67229. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  67230. mat1.multiplyToRef(mat2, mat1);
  67231. }
  67232. if (this._bone1) {
  67233. if (this.slerpAmount < 1) {
  67234. if (!this._slerping) {
  67235. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  67236. }
  67237. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  67238. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  67239. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  67240. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  67241. this._slerping = true;
  67242. }
  67243. else {
  67244. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  67245. this._bone1Mat.copyFrom(mat1);
  67246. this._slerping = false;
  67247. }
  67248. }
  67249. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  67250. this._bone2Ang = angC;
  67251. };
  67252. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67253. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  67254. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67255. return BoneIKController;
  67256. }());
  67257. BABYLON.BoneIKController = BoneIKController;
  67258. })(BABYLON || (BABYLON = {}));
  67259. //# sourceMappingURL=babylon.boneIKController.js.map
  67260. var BABYLON;
  67261. (function (BABYLON) {
  67262. var BoneLookController = /** @class */ (function () {
  67263. /**
  67264. * Create a BoneLookController
  67265. * @param mesh the mesh that the bone belongs to
  67266. * @param bone the bone that will be looking to the target
  67267. * @param target the target Vector3 to look at
  67268. * @param settings optional settings:
  67269. * - maxYaw: the maximum angle the bone will yaw to
  67270. * - minYaw: the minimum angle the bone will yaw to
  67271. * - maxPitch: the maximum angle the bone will pitch to
  67272. * - minPitch: the minimum angle the bone will yaw to
  67273. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  67274. * - upAxis: the up axis of the coordinate system
  67275. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67276. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  67277. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  67278. * - adjustYaw: used to make an adjustment to the yaw of the bone
  67279. * - adjustPitch: used to make an adjustment to the pitch of the bone
  67280. * - adjustRoll: used to make an adjustment to the roll of the bone
  67281. **/
  67282. function BoneLookController(mesh, bone, target, options) {
  67283. /**
  67284. * The up axis of the coordinate system that is used when the bone is rotated.
  67285. */
  67286. this.upAxis = BABYLON.Vector3.Up();
  67287. /**
  67288. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  67289. */
  67290. this.upAxisSpace = BABYLON.Space.LOCAL;
  67291. /**
  67292. * Used to make an adjustment to the yaw of the bone.
  67293. */
  67294. this.adjustYaw = 0;
  67295. /**
  67296. * Used to make an adjustment to the pitch of the bone.
  67297. */
  67298. this.adjustPitch = 0;
  67299. /**
  67300. * Used to make an adjustment to the roll of the bone.
  67301. */
  67302. this.adjustRoll = 0;
  67303. /**
  67304. * 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).
  67305. */
  67306. this.slerpAmount = 1;
  67307. this._boneQuat = BABYLON.Quaternion.Identity();
  67308. this._slerping = false;
  67309. this._firstFrameSkipped = false;
  67310. this._fowardAxis = BABYLON.Vector3.Forward();
  67311. this.mesh = mesh;
  67312. this.bone = bone;
  67313. this.target = target;
  67314. if (options) {
  67315. if (options.adjustYaw) {
  67316. this.adjustYaw = options.adjustYaw;
  67317. }
  67318. if (options.adjustPitch) {
  67319. this.adjustPitch = options.adjustPitch;
  67320. }
  67321. if (options.adjustRoll) {
  67322. this.adjustRoll = options.adjustRoll;
  67323. }
  67324. if (options.maxYaw != null) {
  67325. this.maxYaw = options.maxYaw;
  67326. }
  67327. else {
  67328. this.maxYaw = Math.PI;
  67329. }
  67330. if (options.minYaw != null) {
  67331. this.minYaw = options.minYaw;
  67332. }
  67333. else {
  67334. this.minYaw = -Math.PI;
  67335. }
  67336. if (options.maxPitch != null) {
  67337. this.maxPitch = options.maxPitch;
  67338. }
  67339. else {
  67340. this.maxPitch = Math.PI;
  67341. }
  67342. if (options.minPitch != null) {
  67343. this.minPitch = options.minPitch;
  67344. }
  67345. else {
  67346. this.minPitch = -Math.PI;
  67347. }
  67348. if (options.slerpAmount != null) {
  67349. this.slerpAmount = options.slerpAmount;
  67350. }
  67351. if (options.upAxis != null) {
  67352. this.upAxis = options.upAxis;
  67353. }
  67354. if (options.upAxisSpace != null) {
  67355. this.upAxisSpace = options.upAxisSpace;
  67356. }
  67357. if (options.yawAxis != null || options.pitchAxis != null) {
  67358. var newYawAxis = BABYLON.Axis.Y;
  67359. var newPitchAxis = BABYLON.Axis.X;
  67360. if (options.yawAxis != null) {
  67361. newYawAxis = options.yawAxis.clone();
  67362. newYawAxis.normalize();
  67363. }
  67364. if (options.pitchAxis != null) {
  67365. newPitchAxis = options.pitchAxis.clone();
  67366. newPitchAxis.normalize();
  67367. }
  67368. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  67369. this._transformYawPitch = BABYLON.Matrix.Identity();
  67370. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  67371. this._transformYawPitchInv = this._transformYawPitch.clone();
  67372. this._transformYawPitch.invert();
  67373. }
  67374. }
  67375. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  67376. this.upAxisSpace = BABYLON.Space.LOCAL;
  67377. }
  67378. }
  67379. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  67380. /**
  67381. * Get/set the minimum yaw angle that the bone can look to.
  67382. */
  67383. get: function () {
  67384. return this._minYaw;
  67385. },
  67386. set: function (value) {
  67387. this._minYaw = value;
  67388. this._minYawSin = Math.sin(value);
  67389. this._minYawCos = Math.cos(value);
  67390. if (this._maxYaw != null) {
  67391. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67392. this._yawRange = this._maxYaw - this._minYaw;
  67393. }
  67394. },
  67395. enumerable: true,
  67396. configurable: true
  67397. });
  67398. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  67399. /**
  67400. * Get/set the maximum yaw angle that the bone can look to.
  67401. */
  67402. get: function () {
  67403. return this._maxYaw;
  67404. },
  67405. set: function (value) {
  67406. this._maxYaw = value;
  67407. this._maxYawSin = Math.sin(value);
  67408. this._maxYawCos = Math.cos(value);
  67409. if (this._minYaw != null) {
  67410. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  67411. this._yawRange = this._maxYaw - this._minYaw;
  67412. }
  67413. },
  67414. enumerable: true,
  67415. configurable: true
  67416. });
  67417. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  67418. /**
  67419. * Get/set the minimum pitch angle that the bone can look to.
  67420. */
  67421. get: function () {
  67422. return this._minPitch;
  67423. },
  67424. set: function (value) {
  67425. this._minPitch = value;
  67426. this._minPitchTan = Math.tan(value);
  67427. },
  67428. enumerable: true,
  67429. configurable: true
  67430. });
  67431. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  67432. /**
  67433. * Get/set the maximum pitch angle that the bone can look to.
  67434. */
  67435. get: function () {
  67436. return this._maxPitch;
  67437. },
  67438. set: function (value) {
  67439. this._maxPitch = value;
  67440. this._maxPitchTan = Math.tan(value);
  67441. },
  67442. enumerable: true,
  67443. configurable: true
  67444. });
  67445. /**
  67446. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  67447. */
  67448. BoneLookController.prototype.update = function () {
  67449. //skip the first frame when slerping so that the mesh rotation is correct
  67450. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  67451. this._firstFrameSkipped = true;
  67452. return;
  67453. }
  67454. var bone = this.bone;
  67455. var bonePos = BoneLookController._tmpVecs[0];
  67456. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  67457. var target = this.target;
  67458. var _tmpMat1 = BoneLookController._tmpMats[0];
  67459. var _tmpMat2 = BoneLookController._tmpMats[1];
  67460. var mesh = this.mesh;
  67461. var parentBone = bone.getParent();
  67462. var upAxis = BoneLookController._tmpVecs[1];
  67463. upAxis.copyFrom(this.upAxis);
  67464. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  67465. if (this._transformYawPitch) {
  67466. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  67467. }
  67468. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  67469. }
  67470. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  67471. mesh.getDirectionToRef(upAxis, upAxis);
  67472. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  67473. upAxis.normalize();
  67474. }
  67475. }
  67476. var checkYaw = false;
  67477. var checkPitch = false;
  67478. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  67479. checkYaw = true;
  67480. }
  67481. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  67482. checkPitch = true;
  67483. }
  67484. if (checkYaw || checkPitch) {
  67485. var spaceMat = BoneLookController._tmpMats[2];
  67486. var spaceMatInv = BoneLookController._tmpMats[3];
  67487. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  67488. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  67489. }
  67490. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  67491. spaceMat.copyFrom(mesh.getWorldMatrix());
  67492. }
  67493. else {
  67494. var forwardAxis = BoneLookController._tmpVecs[2];
  67495. forwardAxis.copyFrom(this._fowardAxis);
  67496. if (this._transformYawPitch) {
  67497. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  67498. }
  67499. if (parentBone) {
  67500. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  67501. }
  67502. else {
  67503. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  67504. }
  67505. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  67506. rightAxis.normalize();
  67507. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  67508. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  67509. }
  67510. spaceMat.invertToRef(spaceMatInv);
  67511. var xzlen = null;
  67512. if (checkPitch) {
  67513. var localTarget = BoneLookController._tmpVecs[3];
  67514. target.subtractToRef(bonePos, localTarget);
  67515. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67516. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67517. var pitch = Math.atan2(localTarget.y, xzlen);
  67518. var newPitch = pitch;
  67519. if (pitch > this._maxPitch) {
  67520. localTarget.y = this._maxPitchTan * xzlen;
  67521. newPitch = this._maxPitch;
  67522. }
  67523. else if (pitch < this._minPitch) {
  67524. localTarget.y = this._minPitchTan * xzlen;
  67525. newPitch = this._minPitch;
  67526. }
  67527. if (pitch != newPitch) {
  67528. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67529. localTarget.addInPlace(bonePos);
  67530. target = localTarget;
  67531. }
  67532. }
  67533. if (checkYaw) {
  67534. var localTarget = BoneLookController._tmpVecs[4];
  67535. target.subtractToRef(bonePos, localTarget);
  67536. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  67537. var yaw = Math.atan2(localTarget.x, localTarget.z);
  67538. var newYaw = yaw;
  67539. if (yaw > this._maxYaw || yaw < this._minYaw) {
  67540. if (xzlen == null) {
  67541. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67542. }
  67543. if (this._yawRange > Math.PI) {
  67544. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  67545. localTarget.z = this._maxYawCos * xzlen;
  67546. localTarget.x = this._maxYawSin * xzlen;
  67547. newYaw = this._maxYaw;
  67548. }
  67549. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  67550. localTarget.z = this._minYawCos * xzlen;
  67551. localTarget.x = this._minYawSin * xzlen;
  67552. newYaw = this._minYaw;
  67553. }
  67554. }
  67555. else {
  67556. if (yaw > this._maxYaw) {
  67557. localTarget.z = this._maxYawCos * xzlen;
  67558. localTarget.x = this._maxYawSin * xzlen;
  67559. newYaw = this._maxYaw;
  67560. }
  67561. else if (yaw < this._minYaw) {
  67562. localTarget.z = this._minYawCos * xzlen;
  67563. localTarget.x = this._minYawSin * xzlen;
  67564. newYaw = this._minYaw;
  67565. }
  67566. }
  67567. }
  67568. if (this._slerping && this._yawRange > Math.PI) {
  67569. //are we going to be crossing into the min/max region?
  67570. var boneFwd = BoneLookController._tmpVecs[8];
  67571. boneFwd.copyFrom(BABYLON.Axis.Z);
  67572. if (this._transformYawPitch) {
  67573. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  67574. }
  67575. var boneRotMat = BoneLookController._tmpMats[4];
  67576. this._boneQuat.toRotationMatrix(boneRotMat);
  67577. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  67578. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  67579. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  67580. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  67581. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  67582. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  67583. if (angBtwTar > angBtwMidYaw) {
  67584. if (xzlen == null) {
  67585. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  67586. }
  67587. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  67588. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  67589. if (angBtwMin < angBtwMax) {
  67590. newYaw = boneYaw + Math.PI * .75;
  67591. localTarget.z = Math.cos(newYaw) * xzlen;
  67592. localTarget.x = Math.sin(newYaw) * xzlen;
  67593. }
  67594. else {
  67595. newYaw = boneYaw - Math.PI * .75;
  67596. localTarget.z = Math.cos(newYaw) * xzlen;
  67597. localTarget.x = Math.sin(newYaw) * xzlen;
  67598. }
  67599. }
  67600. }
  67601. if (yaw != newYaw) {
  67602. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  67603. localTarget.addInPlace(bonePos);
  67604. target = localTarget;
  67605. }
  67606. }
  67607. }
  67608. var zaxis = BoneLookController._tmpVecs[5];
  67609. var xaxis = BoneLookController._tmpVecs[6];
  67610. var yaxis = BoneLookController._tmpVecs[7];
  67611. var _tmpQuat = BoneLookController._tmpQuat;
  67612. target.subtractToRef(bonePos, zaxis);
  67613. zaxis.normalize();
  67614. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  67615. xaxis.normalize();
  67616. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  67617. yaxis.normalize();
  67618. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  67619. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  67620. return;
  67621. }
  67622. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  67623. return;
  67624. }
  67625. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  67626. return;
  67627. }
  67628. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  67629. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  67630. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  67631. }
  67632. if (this.slerpAmount < 1) {
  67633. if (!this._slerping) {
  67634. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  67635. }
  67636. if (this._transformYawPitch) {
  67637. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67638. }
  67639. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  67640. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  67641. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  67642. this._slerping = true;
  67643. }
  67644. else {
  67645. if (this._transformYawPitch) {
  67646. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67647. }
  67648. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  67649. this._slerping = false;
  67650. }
  67651. };
  67652. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  67653. var angDiff = ang2 - ang1;
  67654. angDiff %= Math.PI * 2;
  67655. if (angDiff > Math.PI) {
  67656. angDiff -= Math.PI * 2;
  67657. }
  67658. else if (angDiff < -Math.PI) {
  67659. angDiff += Math.PI * 2;
  67660. }
  67661. return angDiff;
  67662. };
  67663. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  67664. ang1 %= (2 * Math.PI);
  67665. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67666. ang2 %= (2 * Math.PI);
  67667. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67668. var ab = 0;
  67669. if (ang1 < ang2) {
  67670. ab = ang2 - ang1;
  67671. }
  67672. else {
  67673. ab = ang1 - ang2;
  67674. }
  67675. if (ab > Math.PI) {
  67676. ab = Math.PI * 2 - ab;
  67677. }
  67678. return ab;
  67679. };
  67680. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  67681. ang %= (2 * Math.PI);
  67682. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  67683. ang1 %= (2 * Math.PI);
  67684. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67685. ang2 %= (2 * Math.PI);
  67686. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67687. if (ang1 < ang2) {
  67688. if (ang > ang1 && ang < ang2) {
  67689. return true;
  67690. }
  67691. }
  67692. else {
  67693. if (ang > ang2 && ang < ang1) {
  67694. return true;
  67695. }
  67696. }
  67697. return false;
  67698. };
  67699. 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()];
  67700. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  67701. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67702. return BoneLookController;
  67703. }());
  67704. BABYLON.BoneLookController = BoneLookController;
  67705. })(BABYLON || (BABYLON = {}));
  67706. //# sourceMappingURL=babylon.boneLookController.js.map
  67707. var BABYLON;
  67708. (function (BABYLON) {
  67709. var Skeleton = /** @class */ (function () {
  67710. function Skeleton(name, id, scene) {
  67711. this.name = name;
  67712. this.id = id;
  67713. this.bones = new Array();
  67714. this.needInitialSkinMatrix = false;
  67715. this._isDirty = true;
  67716. this._meshesWithPoseMatrix = new Array();
  67717. this._identity = BABYLON.Matrix.Identity();
  67718. this._ranges = {};
  67719. this._lastAbsoluteTransformsUpdateId = -1;
  67720. // Events
  67721. /**
  67722. * An event triggered before computing the skeleton's matrices
  67723. * @type {BABYLON.Observable}
  67724. */
  67725. this.onBeforeComputeObservable = new BABYLON.Observable();
  67726. this.bones = [];
  67727. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67728. scene.skeletons.push(this);
  67729. //make sure it will recalculate the matrix next time prepare is called.
  67730. this._isDirty = true;
  67731. }
  67732. // Members
  67733. Skeleton.prototype.getTransformMatrices = function (mesh) {
  67734. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  67735. return mesh._bonesTransformMatrices;
  67736. }
  67737. if (!this._transformMatrices) {
  67738. this.prepare();
  67739. }
  67740. return this._transformMatrices;
  67741. };
  67742. Skeleton.prototype.getScene = function () {
  67743. return this._scene;
  67744. };
  67745. // Methods
  67746. /**
  67747. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  67748. */
  67749. Skeleton.prototype.toString = function (fullDetails) {
  67750. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  67751. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  67752. if (fullDetails) {
  67753. ret += ", Ranges: {";
  67754. var first = true;
  67755. for (var name_1 in this._ranges) {
  67756. if (first) {
  67757. ret += ", ";
  67758. first = false;
  67759. }
  67760. ret += name_1;
  67761. }
  67762. ret += "}";
  67763. }
  67764. return ret;
  67765. };
  67766. /**
  67767. * Get bone's index searching by name
  67768. * @param {string} name is bone's name to search for
  67769. * @return {number} Indice of the bone. Returns -1 if not found
  67770. */
  67771. Skeleton.prototype.getBoneIndexByName = function (name) {
  67772. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  67773. if (this.bones[boneIndex].name === name) {
  67774. return boneIndex;
  67775. }
  67776. }
  67777. return -1;
  67778. };
  67779. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  67780. // check name not already in use
  67781. if (!this._ranges[name]) {
  67782. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  67783. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67784. if (this.bones[i].animations[0]) {
  67785. this.bones[i].animations[0].createRange(name, from, to);
  67786. }
  67787. }
  67788. }
  67789. };
  67790. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  67791. if (deleteFrames === void 0) { deleteFrames = true; }
  67792. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67793. if (this.bones[i].animations[0]) {
  67794. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  67795. }
  67796. }
  67797. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  67798. };
  67799. Skeleton.prototype.getAnimationRange = function (name) {
  67800. return this._ranges[name];
  67801. };
  67802. /**
  67803. * Returns as an Array, all AnimationRanges defined on this skeleton
  67804. */
  67805. Skeleton.prototype.getAnimationRanges = function () {
  67806. var animationRanges = [];
  67807. var name;
  67808. var i = 0;
  67809. for (name in this._ranges) {
  67810. animationRanges[i] = this._ranges[name];
  67811. i++;
  67812. }
  67813. return animationRanges;
  67814. };
  67815. /**
  67816. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  67817. */
  67818. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  67819. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  67820. if (this._ranges[name] || !source.getAnimationRange(name)) {
  67821. return false;
  67822. }
  67823. var ret = true;
  67824. var frameOffset = this._getHighestAnimationFrame() + 1;
  67825. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  67826. var boneDict = {};
  67827. var sourceBones = source.bones;
  67828. var nBones;
  67829. var i;
  67830. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  67831. boneDict[sourceBones[i].name] = sourceBones[i];
  67832. }
  67833. if (this.bones.length !== sourceBones.length) {
  67834. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  67835. ret = false;
  67836. }
  67837. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  67838. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  67839. var boneName = this.bones[i].name;
  67840. var sourceBone = boneDict[boneName];
  67841. if (sourceBone) {
  67842. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  67843. }
  67844. else {
  67845. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  67846. ret = false;
  67847. }
  67848. }
  67849. // do not call createAnimationRange(), since it also is done to bones, which was already done
  67850. var range = source.getAnimationRange(name);
  67851. if (range) {
  67852. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  67853. }
  67854. return ret;
  67855. };
  67856. Skeleton.prototype.returnToRest = function () {
  67857. for (var index = 0; index < this.bones.length; index++) {
  67858. this.bones[index].returnToRest();
  67859. }
  67860. };
  67861. Skeleton.prototype._getHighestAnimationFrame = function () {
  67862. var ret = 0;
  67863. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67864. if (this.bones[i].animations[0]) {
  67865. var highest = this.bones[i].animations[0].getHighestFrame();
  67866. if (ret < highest) {
  67867. ret = highest;
  67868. }
  67869. }
  67870. }
  67871. return ret;
  67872. };
  67873. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  67874. var range = this.getAnimationRange(name);
  67875. if (!range) {
  67876. return null;
  67877. }
  67878. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  67879. };
  67880. Skeleton.prototype._markAsDirty = function () {
  67881. this._isDirty = true;
  67882. };
  67883. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  67884. this._meshesWithPoseMatrix.push(mesh);
  67885. };
  67886. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  67887. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  67888. if (index > -1) {
  67889. this._meshesWithPoseMatrix.splice(index, 1);
  67890. }
  67891. };
  67892. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  67893. this.onBeforeComputeObservable.notifyObservers(this);
  67894. for (var index = 0; index < this.bones.length; index++) {
  67895. var bone = this.bones[index];
  67896. var parentBone = bone.getParent();
  67897. if (parentBone) {
  67898. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  67899. }
  67900. else {
  67901. if (initialSkinMatrix) {
  67902. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  67903. }
  67904. else {
  67905. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  67906. }
  67907. }
  67908. if (bone._index !== -1) {
  67909. var mappedIndex = bone._index === null ? index : bone._index;
  67910. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  67911. }
  67912. }
  67913. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  67914. };
  67915. Skeleton.prototype.prepare = function () {
  67916. if (!this._isDirty) {
  67917. return;
  67918. }
  67919. if (this.needInitialSkinMatrix) {
  67920. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  67921. var mesh = this._meshesWithPoseMatrix[index];
  67922. var poseMatrix = mesh.getPoseMatrix();
  67923. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  67924. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67925. }
  67926. if (this._synchronizedWithMesh !== mesh) {
  67927. this._synchronizedWithMesh = mesh;
  67928. // Prepare bones
  67929. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  67930. var bone = this.bones[boneIndex];
  67931. if (!bone.getParent()) {
  67932. var matrix = bone.getBaseMatrix();
  67933. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  67934. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  67935. }
  67936. }
  67937. }
  67938. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  67939. }
  67940. }
  67941. else {
  67942. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  67943. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67944. }
  67945. this._computeTransformMatrices(this._transformMatrices, null);
  67946. }
  67947. this._isDirty = false;
  67948. this._scene._activeBones.addCount(this.bones.length, false);
  67949. };
  67950. Skeleton.prototype.getAnimatables = function () {
  67951. if (!this._animatables || this._animatables.length !== this.bones.length) {
  67952. this._animatables = [];
  67953. for (var index = 0; index < this.bones.length; index++) {
  67954. this._animatables.push(this.bones[index]);
  67955. }
  67956. }
  67957. return this._animatables;
  67958. };
  67959. Skeleton.prototype.clone = function (name, id) {
  67960. var result = new Skeleton(name, id || name, this._scene);
  67961. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67962. for (var index = 0; index < this.bones.length; index++) {
  67963. var source = this.bones[index];
  67964. var parentBone = null;
  67965. var parent_1 = source.getParent();
  67966. if (parent_1) {
  67967. var parentIndex = this.bones.indexOf(parent_1);
  67968. parentBone = result.bones[parentIndex];
  67969. }
  67970. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  67971. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  67972. }
  67973. if (this._ranges) {
  67974. result._ranges = {};
  67975. for (var rangeName in this._ranges) {
  67976. var range = this._ranges[rangeName];
  67977. if (range) {
  67978. result._ranges[rangeName] = range.clone();
  67979. }
  67980. }
  67981. }
  67982. this._isDirty = true;
  67983. return result;
  67984. };
  67985. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  67986. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  67987. this.bones.forEach(function (bone) {
  67988. bone.animations.forEach(function (animation) {
  67989. animation.enableBlending = true;
  67990. animation.blendingSpeed = blendingSpeed;
  67991. });
  67992. });
  67993. };
  67994. Skeleton.prototype.dispose = function () {
  67995. this._meshesWithPoseMatrix = [];
  67996. // Animations
  67997. this.getScene().stopAnimation(this);
  67998. // Remove from scene
  67999. this.getScene().removeSkeleton(this);
  68000. };
  68001. Skeleton.prototype.serialize = function () {
  68002. var serializationObject = {};
  68003. serializationObject.name = this.name;
  68004. serializationObject.id = this.id;
  68005. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  68006. serializationObject.bones = [];
  68007. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  68008. for (var index = 0; index < this.bones.length; index++) {
  68009. var bone = this.bones[index];
  68010. var parent_2 = bone.getParent();
  68011. var serializedBone = {
  68012. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  68013. name: bone.name,
  68014. matrix: bone.getBaseMatrix().toArray(),
  68015. rest: bone.getRestPose().toArray()
  68016. };
  68017. serializationObject.bones.push(serializedBone);
  68018. if (bone.length) {
  68019. serializedBone.length = bone.length;
  68020. }
  68021. if (bone.animations && bone.animations.length > 0) {
  68022. serializedBone.animation = bone.animations[0].serialize();
  68023. }
  68024. serializationObject.ranges = [];
  68025. for (var name in this._ranges) {
  68026. var source = this._ranges[name];
  68027. if (!source) {
  68028. continue;
  68029. }
  68030. var range = {};
  68031. range.name = name;
  68032. range.from = source.from;
  68033. range.to = source.to;
  68034. serializationObject.ranges.push(range);
  68035. }
  68036. }
  68037. return serializationObject;
  68038. };
  68039. Skeleton.Parse = function (parsedSkeleton, scene) {
  68040. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  68041. if (parsedSkeleton.dimensionsAtRest) {
  68042. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  68043. }
  68044. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  68045. var index;
  68046. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  68047. var parsedBone = parsedSkeleton.bones[index];
  68048. var parentBone = null;
  68049. if (parsedBone.parentBoneIndex > -1) {
  68050. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  68051. }
  68052. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  68053. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  68054. if (parsedBone.length) {
  68055. bone.length = parsedBone.length;
  68056. }
  68057. if (parsedBone.animation) {
  68058. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  68059. }
  68060. }
  68061. // placed after bones, so createAnimationRange can cascade down
  68062. if (parsedSkeleton.ranges) {
  68063. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  68064. var data = parsedSkeleton.ranges[index];
  68065. skeleton.createAnimationRange(data.name, data.from, data.to);
  68066. }
  68067. }
  68068. return skeleton;
  68069. };
  68070. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  68071. if (forceUpdate === void 0) { forceUpdate = false; }
  68072. var renderId = this._scene.getRenderId();
  68073. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  68074. this.bones[0].computeAbsoluteTransforms();
  68075. this._lastAbsoluteTransformsUpdateId = renderId;
  68076. }
  68077. };
  68078. Skeleton.prototype.getPoseMatrix = function () {
  68079. var poseMatrix = null;
  68080. if (this._meshesWithPoseMatrix.length > 0) {
  68081. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  68082. }
  68083. return poseMatrix;
  68084. };
  68085. Skeleton.prototype.sortBones = function () {
  68086. var bones = new Array();
  68087. var visited = new Array(this.bones.length);
  68088. for (var index = 0; index < this.bones.length; index++) {
  68089. this._sortBones(index, bones, visited);
  68090. }
  68091. this.bones = bones;
  68092. };
  68093. Skeleton.prototype._sortBones = function (index, bones, visited) {
  68094. if (visited[index]) {
  68095. return;
  68096. }
  68097. visited[index] = true;
  68098. var bone = this.bones[index];
  68099. if (bone._index === undefined) {
  68100. bone._index = index;
  68101. }
  68102. var parentBone = bone.getParent();
  68103. if (parentBone) {
  68104. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  68105. }
  68106. bones.push(bone);
  68107. };
  68108. return Skeleton;
  68109. }());
  68110. BABYLON.Skeleton = Skeleton;
  68111. })(BABYLON || (BABYLON = {}));
  68112. //# sourceMappingURL=babylon.skeleton.js.map
  68113. var BABYLON;
  68114. (function (BABYLON) {
  68115. var SphericalPolynomial = /** @class */ (function () {
  68116. function SphericalPolynomial() {
  68117. this.x = BABYLON.Vector3.Zero();
  68118. this.y = BABYLON.Vector3.Zero();
  68119. this.z = BABYLON.Vector3.Zero();
  68120. this.xx = BABYLON.Vector3.Zero();
  68121. this.yy = BABYLON.Vector3.Zero();
  68122. this.zz = BABYLON.Vector3.Zero();
  68123. this.xy = BABYLON.Vector3.Zero();
  68124. this.yz = BABYLON.Vector3.Zero();
  68125. this.zx = BABYLON.Vector3.Zero();
  68126. }
  68127. SphericalPolynomial.prototype.addAmbient = function (color) {
  68128. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68129. this.xx = this.xx.add(colorVector);
  68130. this.yy = this.yy.add(colorVector);
  68131. this.zz = this.zz.add(colorVector);
  68132. };
  68133. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  68134. var result = new SphericalPolynomial();
  68135. result.x = harmonics.L11.scale(1.02333);
  68136. result.y = harmonics.L1_1.scale(1.02333);
  68137. result.z = harmonics.L10.scale(1.02333);
  68138. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  68139. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  68140. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  68141. result.yz = harmonics.L2_1.scale(0.858086);
  68142. result.zx = harmonics.L21.scale(0.858086);
  68143. result.xy = harmonics.L2_2.scale(0.858086);
  68144. result.scale(1.0 / Math.PI);
  68145. return result;
  68146. };
  68147. SphericalPolynomial.prototype.scale = function (scale) {
  68148. this.x = this.x.scale(scale);
  68149. this.y = this.y.scale(scale);
  68150. this.z = this.z.scale(scale);
  68151. this.xx = this.xx.scale(scale);
  68152. this.yy = this.yy.scale(scale);
  68153. this.zz = this.zz.scale(scale);
  68154. this.yz = this.yz.scale(scale);
  68155. this.zx = this.zx.scale(scale);
  68156. this.xy = this.xy.scale(scale);
  68157. };
  68158. return SphericalPolynomial;
  68159. }());
  68160. BABYLON.SphericalPolynomial = SphericalPolynomial;
  68161. var SphericalHarmonics = /** @class */ (function () {
  68162. function SphericalHarmonics() {
  68163. this.L00 = BABYLON.Vector3.Zero();
  68164. this.L1_1 = BABYLON.Vector3.Zero();
  68165. this.L10 = BABYLON.Vector3.Zero();
  68166. this.L11 = BABYLON.Vector3.Zero();
  68167. this.L2_2 = BABYLON.Vector3.Zero();
  68168. this.L2_1 = BABYLON.Vector3.Zero();
  68169. this.L20 = BABYLON.Vector3.Zero();
  68170. this.L21 = BABYLON.Vector3.Zero();
  68171. this.L22 = BABYLON.Vector3.Zero();
  68172. }
  68173. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  68174. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  68175. var c = colorVector.scale(deltaSolidAngle);
  68176. this.L00 = this.L00.add(c.scale(0.282095));
  68177. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  68178. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  68179. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  68180. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  68181. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  68182. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  68183. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  68184. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  68185. };
  68186. SphericalHarmonics.prototype.scale = function (scale) {
  68187. this.L00 = this.L00.scale(scale);
  68188. this.L1_1 = this.L1_1.scale(scale);
  68189. this.L10 = this.L10.scale(scale);
  68190. this.L11 = this.L11.scale(scale);
  68191. this.L2_2 = this.L2_2.scale(scale);
  68192. this.L2_1 = this.L2_1.scale(scale);
  68193. this.L20 = this.L20.scale(scale);
  68194. this.L21 = this.L21.scale(scale);
  68195. this.L22 = this.L22.scale(scale);
  68196. };
  68197. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  68198. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  68199. //
  68200. // E_lm = A_l * L_lm
  68201. //
  68202. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  68203. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  68204. // the scaling factors are given in equation 9.
  68205. // Constant (Band 0)
  68206. this.L00 = this.L00.scale(3.141593);
  68207. // Linear (Band 1)
  68208. this.L1_1 = this.L1_1.scale(2.094395);
  68209. this.L10 = this.L10.scale(2.094395);
  68210. this.L11 = this.L11.scale(2.094395);
  68211. // Quadratic (Band 2)
  68212. this.L2_2 = this.L2_2.scale(0.785398);
  68213. this.L2_1 = this.L2_1.scale(0.785398);
  68214. this.L20 = this.L20.scale(0.785398);
  68215. this.L21 = this.L21.scale(0.785398);
  68216. this.L22 = this.L22.scale(0.785398);
  68217. };
  68218. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  68219. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  68220. // L = (1/pi) * E * rho
  68221. //
  68222. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  68223. this.scale(1.0 / Math.PI);
  68224. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  68225. // (The pixel shader must apply albedo after texture fetches, etc).
  68226. };
  68227. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  68228. var result = new SphericalHarmonics();
  68229. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  68230. result.L1_1 = polynomial.y.scale(0.977204);
  68231. result.L10 = polynomial.z.scale(0.977204);
  68232. result.L11 = polynomial.x.scale(0.977204);
  68233. result.L2_2 = polynomial.xy.scale(1.16538);
  68234. result.L2_1 = polynomial.yz.scale(1.16538);
  68235. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  68236. result.L21 = polynomial.zx.scale(1.16538);
  68237. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  68238. result.scale(Math.PI);
  68239. return result;
  68240. };
  68241. return SphericalHarmonics;
  68242. }());
  68243. BABYLON.SphericalHarmonics = SphericalHarmonics;
  68244. })(BABYLON || (BABYLON = {}));
  68245. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  68246. var BABYLON;
  68247. (function (BABYLON) {
  68248. var FileFaceOrientation = /** @class */ (function () {
  68249. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  68250. this.name = name;
  68251. this.worldAxisForNormal = worldAxisForNormal;
  68252. this.worldAxisForFileX = worldAxisForFileX;
  68253. this.worldAxisForFileY = worldAxisForFileY;
  68254. }
  68255. return FileFaceOrientation;
  68256. }());
  68257. ;
  68258. /**
  68259. * Helper class dealing with the extraction of spherical polynomial dataArray
  68260. * from a cube map.
  68261. */
  68262. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  68263. function CubeMapToSphericalPolynomialTools() {
  68264. }
  68265. /**
  68266. * Converts a texture to the according Spherical Polynomial data.
  68267. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68268. *
  68269. * @param texture The texture to extract the information from.
  68270. * @return The Spherical Polynomial data.
  68271. */
  68272. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  68273. if (!texture.isCube) {
  68274. // Only supports cube Textures currently.
  68275. return null;
  68276. }
  68277. var size = texture.getSize().width;
  68278. var right = texture.readPixels(0);
  68279. var left = texture.readPixels(1);
  68280. var up;
  68281. var down;
  68282. if (texture.isRenderTarget) {
  68283. up = texture.readPixels(3);
  68284. down = texture.readPixels(2);
  68285. }
  68286. else {
  68287. up = texture.readPixels(2);
  68288. down = texture.readPixels(3);
  68289. }
  68290. var front = texture.readPixels(4);
  68291. var back = texture.readPixels(5);
  68292. var gammaSpace = texture.gammaSpace;
  68293. // Always read as RGBA.
  68294. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  68295. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68296. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68297. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68298. }
  68299. var cubeInfo = {
  68300. size: size,
  68301. right: right,
  68302. left: left,
  68303. up: up,
  68304. down: down,
  68305. front: front,
  68306. back: back,
  68307. format: format,
  68308. type: type,
  68309. gammaSpace: gammaSpace,
  68310. };
  68311. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  68312. };
  68313. /**
  68314. * Converts a cubemap to the according Spherical Polynomial data.
  68315. * This extracts the first 3 orders only as they are the only one used in the lighting.
  68316. *
  68317. * @param cubeInfo The Cube map to extract the information from.
  68318. * @return The Spherical Polynomial data.
  68319. */
  68320. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  68321. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  68322. var totalSolidAngle = 0.0;
  68323. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  68324. var du = 2.0 / cubeInfo.size;
  68325. var dv = du;
  68326. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  68327. var minUV = du * 0.5 - 1.0;
  68328. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68329. var fileFace = this.FileFaces[faceIndex];
  68330. var dataArray = cubeInfo[fileFace.name];
  68331. var v = minUV;
  68332. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  68333. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  68334. // Because SP is still linear, so summation is fine in that basis.
  68335. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  68336. for (var y = 0; y < cubeInfo.size; y++) {
  68337. var u = minUV;
  68338. for (var x = 0; x < cubeInfo.size; x++) {
  68339. // World direction (not normalised)
  68340. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  68341. worldDirection.normalize();
  68342. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  68343. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  68344. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  68345. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  68346. // Handle Integer types.
  68347. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68348. r /= 255;
  68349. g /= 255;
  68350. b /= 255;
  68351. }
  68352. // Handle Gamma space textures.
  68353. if (cubeInfo.gammaSpace) {
  68354. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  68355. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  68356. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  68357. }
  68358. var color = new BABYLON.Color3(r, g, b);
  68359. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  68360. totalSolidAngle += deltaSolidAngle;
  68361. u += du;
  68362. }
  68363. v += dv;
  68364. }
  68365. }
  68366. // Solid angle for entire sphere is 4*pi
  68367. var sphereSolidAngle = 4.0 * Math.PI;
  68368. // Adjust the solid angle to allow for how many faces we processed.
  68369. var facesProcessed = 6.0;
  68370. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  68371. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  68372. // This is needed because the numerical integration over the cube uses a
  68373. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  68374. // and also to compensate for accumulative error due to float precision in the summation.
  68375. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  68376. sphericalHarmonics.scale(correctionFactor);
  68377. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  68378. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  68379. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  68380. };
  68381. CubeMapToSphericalPolynomialTools.FileFaces = [
  68382. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  68383. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  68384. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  68385. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  68386. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  68387. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  68388. ];
  68389. return CubeMapToSphericalPolynomialTools;
  68390. }());
  68391. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  68392. })(BABYLON || (BABYLON = {}));
  68393. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  68394. var BABYLON;
  68395. (function (BABYLON) {
  68396. /**
  68397. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  68398. */
  68399. var PanoramaToCubeMapTools = /** @class */ (function () {
  68400. function PanoramaToCubeMapTools() {
  68401. }
  68402. /**
  68403. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  68404. *
  68405. * @param float32Array The source data.
  68406. * @param inputWidth The width of the input panorama.
  68407. * @param inputhHeight The height of the input panorama.
  68408. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  68409. * @return The cubemap data
  68410. */
  68411. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  68412. if (!float32Array) {
  68413. throw "ConvertPanoramaToCubemap: input cannot be null";
  68414. }
  68415. if (float32Array.length != inputWidth * inputHeight * 3) {
  68416. throw "ConvertPanoramaToCubemap: input size is wrong";
  68417. }
  68418. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  68419. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  68420. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  68421. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  68422. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  68423. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  68424. return {
  68425. front: textureFront,
  68426. back: textureBack,
  68427. left: textureLeft,
  68428. right: textureRight,
  68429. up: textureUp,
  68430. down: textureDown,
  68431. size: size,
  68432. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  68433. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  68434. gammaSpace: false,
  68435. };
  68436. };
  68437. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  68438. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  68439. var textureArray = new Float32Array(buffer);
  68440. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  68441. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  68442. var dy = 1 / texSize;
  68443. var fy = 0;
  68444. for (var y = 0; y < texSize; y++) {
  68445. var xv1 = faceData[0];
  68446. var xv2 = faceData[2];
  68447. for (var x = 0; x < texSize; x++) {
  68448. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  68449. v.normalize();
  68450. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  68451. // 3 channels per pixels
  68452. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  68453. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  68454. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  68455. xv1 = xv1.add(rotDX1);
  68456. xv2 = xv2.add(rotDX2);
  68457. }
  68458. fy += dy;
  68459. }
  68460. return textureArray;
  68461. };
  68462. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  68463. var theta = Math.atan2(vDir.z, vDir.x);
  68464. var phi = Math.acos(vDir.y);
  68465. while (theta < -Math.PI)
  68466. theta += 2 * Math.PI;
  68467. while (theta > Math.PI)
  68468. theta -= 2 * Math.PI;
  68469. var dx = theta / Math.PI;
  68470. var dy = phi / Math.PI;
  68471. // recenter.
  68472. dx = dx * 0.5 + 0.5;
  68473. var px = Math.round(dx * inputWidth);
  68474. if (px < 0)
  68475. px = 0;
  68476. else if (px >= inputWidth)
  68477. px = inputWidth - 1;
  68478. var py = Math.round(dy * inputHeight);
  68479. if (py < 0)
  68480. py = 0;
  68481. else if (py >= inputHeight)
  68482. py = inputHeight - 1;
  68483. var inputY = (inputHeight - py - 1);
  68484. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  68485. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  68486. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  68487. return {
  68488. r: r,
  68489. g: g,
  68490. b: b
  68491. };
  68492. };
  68493. PanoramaToCubeMapTools.FACE_FRONT = [
  68494. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68495. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68496. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68497. new BABYLON.Vector3(1.0, 1.0, -1.0)
  68498. ];
  68499. PanoramaToCubeMapTools.FACE_BACK = [
  68500. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68501. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68502. new BABYLON.Vector3(1.0, 1.0, 1.0),
  68503. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  68504. ];
  68505. PanoramaToCubeMapTools.FACE_RIGHT = [
  68506. new BABYLON.Vector3(1.0, -1.0, -1.0),
  68507. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68508. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68509. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68510. ];
  68511. PanoramaToCubeMapTools.FACE_LEFT = [
  68512. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68513. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68514. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68515. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  68516. ];
  68517. PanoramaToCubeMapTools.FACE_DOWN = [
  68518. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  68519. new BABYLON.Vector3(1.0, 1.0, -1.0),
  68520. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  68521. new BABYLON.Vector3(1.0, 1.0, 1.0)
  68522. ];
  68523. PanoramaToCubeMapTools.FACE_UP = [
  68524. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  68525. new BABYLON.Vector3(1.0, -1.0, 1.0),
  68526. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  68527. new BABYLON.Vector3(1.0, -1.0, -1.0)
  68528. ];
  68529. return PanoramaToCubeMapTools;
  68530. }());
  68531. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  68532. })(BABYLON || (BABYLON = {}));
  68533. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  68534. var BABYLON;
  68535. (function (BABYLON) {
  68536. ;
  68537. /**
  68538. * This groups tools to convert HDR texture to native colors array.
  68539. */
  68540. var HDRTools = /** @class */ (function () {
  68541. function HDRTools() {
  68542. }
  68543. HDRTools.Ldexp = function (mantissa, exponent) {
  68544. if (exponent > 1023) {
  68545. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  68546. }
  68547. if (exponent < -1074) {
  68548. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  68549. }
  68550. return mantissa * Math.pow(2, exponent);
  68551. };
  68552. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  68553. if (exponent > 0) {
  68554. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  68555. float32array[index + 0] = red * exponent;
  68556. float32array[index + 1] = green * exponent;
  68557. float32array[index + 2] = blue * exponent;
  68558. }
  68559. else {
  68560. float32array[index + 0] = 0;
  68561. float32array[index + 1] = 0;
  68562. float32array[index + 2] = 0;
  68563. }
  68564. };
  68565. HDRTools.readStringLine = function (uint8array, startIndex) {
  68566. var line = "";
  68567. var character = "";
  68568. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  68569. character = String.fromCharCode(uint8array[i]);
  68570. if (character == "\n") {
  68571. break;
  68572. }
  68573. line += character;
  68574. }
  68575. return line;
  68576. };
  68577. /**
  68578. * Reads header information from an RGBE texture stored in a native array.
  68579. * More information on this format are available here:
  68580. * https://en.wikipedia.org/wiki/RGBE_image_format
  68581. *
  68582. * @param uint8array The binary file stored in native array.
  68583. * @return The header information.
  68584. */
  68585. HDRTools.RGBE_ReadHeader = function (uint8array) {
  68586. var height = 0;
  68587. var width = 0;
  68588. var line = this.readStringLine(uint8array, 0);
  68589. if (line[0] != '#' || line[1] != '?') {
  68590. throw "Bad HDR Format.";
  68591. }
  68592. var endOfHeader = false;
  68593. var findFormat = false;
  68594. var lineIndex = 0;
  68595. do {
  68596. lineIndex += (line.length + 1);
  68597. line = this.readStringLine(uint8array, lineIndex);
  68598. if (line == "FORMAT=32-bit_rle_rgbe") {
  68599. findFormat = true;
  68600. }
  68601. else if (line.length == 0) {
  68602. endOfHeader = true;
  68603. }
  68604. } while (!endOfHeader);
  68605. if (!findFormat) {
  68606. throw "HDR Bad header format, unsupported FORMAT";
  68607. }
  68608. lineIndex += (line.length + 1);
  68609. line = this.readStringLine(uint8array, lineIndex);
  68610. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  68611. var match = sizeRegexp.exec(line);
  68612. // TODO. Support +Y and -X if needed.
  68613. if (!match || match.length < 3) {
  68614. throw "HDR Bad header format, no size";
  68615. }
  68616. width = parseInt(match[2]);
  68617. height = parseInt(match[1]);
  68618. if (width < 8 || width > 0x7fff) {
  68619. throw "HDR Bad header format, unsupported size";
  68620. }
  68621. lineIndex += (line.length + 1);
  68622. return {
  68623. height: height,
  68624. width: width,
  68625. dataPosition: lineIndex
  68626. };
  68627. };
  68628. /**
  68629. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  68630. * This RGBE texture needs to store the information as a panorama.
  68631. *
  68632. * More information on this format are available here:
  68633. * https://en.wikipedia.org/wiki/RGBE_image_format
  68634. *
  68635. * @param buffer The binary file stored in an array buffer.
  68636. * @param size The expected size of the extracted cubemap.
  68637. * @return The Cube Map information.
  68638. */
  68639. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  68640. var uint8array = new Uint8Array(buffer);
  68641. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  68642. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68643. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  68644. return cubeMapData;
  68645. };
  68646. /**
  68647. * Returns the pixels data extracted from an RGBE texture.
  68648. * This pixels will be stored left to right up to down in the R G B order in one array.
  68649. *
  68650. * More information on this format are available here:
  68651. * https://en.wikipedia.org/wiki/RGBE_image_format
  68652. *
  68653. * @param uint8array The binary file stored in an array buffer.
  68654. * @param hdrInfo The header information of the file.
  68655. * @return The pixels data in RGB right to left up to down order.
  68656. */
  68657. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  68658. // Keep for multi format supports.
  68659. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68660. };
  68661. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  68662. var num_scanlines = hdrInfo.height;
  68663. var scanline_width = hdrInfo.width;
  68664. var a, b, c, d, count;
  68665. var dataIndex = hdrInfo.dataPosition;
  68666. var index = 0, endIndex = 0, i = 0;
  68667. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  68668. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  68669. // 3 channels of 4 bytes per pixel in float.
  68670. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  68671. var resultArray = new Float32Array(resultBuffer);
  68672. // read in each successive scanline
  68673. while (num_scanlines > 0) {
  68674. a = uint8array[dataIndex++];
  68675. b = uint8array[dataIndex++];
  68676. c = uint8array[dataIndex++];
  68677. d = uint8array[dataIndex++];
  68678. if (a != 2 || b != 2 || (c & 0x80)) {
  68679. // this file is not run length encoded
  68680. throw "HDR Bad header format, not RLE";
  68681. }
  68682. if (((c << 8) | d) != scanline_width) {
  68683. throw "HDR Bad header format, wrong scan line width";
  68684. }
  68685. index = 0;
  68686. // read each of the four channels for the scanline into the buffer
  68687. for (i = 0; i < 4; i++) {
  68688. endIndex = (i + 1) * scanline_width;
  68689. while (index < endIndex) {
  68690. a = uint8array[dataIndex++];
  68691. b = uint8array[dataIndex++];
  68692. if (a > 128) {
  68693. // a run of the same value
  68694. count = a - 128;
  68695. if ((count == 0) || (count > endIndex - index)) {
  68696. throw "HDR Bad Format, bad scanline data (run)";
  68697. }
  68698. while (count-- > 0) {
  68699. scanLineArray[index++] = b;
  68700. }
  68701. }
  68702. else {
  68703. // a non-run
  68704. count = a;
  68705. if ((count == 0) || (count > endIndex - index)) {
  68706. throw "HDR Bad Format, bad scanline data (non-run)";
  68707. }
  68708. scanLineArray[index++] = b;
  68709. if (--count > 0) {
  68710. for (var j = 0; j < count; j++) {
  68711. scanLineArray[index++] = uint8array[dataIndex++];
  68712. }
  68713. }
  68714. }
  68715. }
  68716. }
  68717. // now convert data from buffer into floats
  68718. for (i = 0; i < scanline_width; i++) {
  68719. a = scanLineArray[i];
  68720. b = scanLineArray[i + scanline_width];
  68721. c = scanLineArray[i + 2 * scanline_width];
  68722. d = scanLineArray[i + 3 * scanline_width];
  68723. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  68724. }
  68725. num_scanlines--;
  68726. }
  68727. return resultArray;
  68728. };
  68729. return HDRTools;
  68730. }());
  68731. BABYLON.HDRTools = HDRTools;
  68732. })(BABYLON || (BABYLON = {}));
  68733. //# sourceMappingURL=babylon.hdr.js.map
  68734. var BABYLON;
  68735. (function (BABYLON) {
  68736. /**
  68737. * This represents a texture coming from an HDR input.
  68738. *
  68739. * The only supported format is currently panorama picture stored in RGBE format.
  68740. * Example of such files can be found on HDRLib: http://hdrlib.com/
  68741. */
  68742. var HDRCubeTexture = /** @class */ (function (_super) {
  68743. __extends(HDRCubeTexture, _super);
  68744. /**
  68745. * Instantiates an HDRTexture from the following parameters.
  68746. *
  68747. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  68748. * @param scene The scene the texture will be used in
  68749. * @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.
  68750. * @param noMipmap Forces to not generate the mipmap if true
  68751. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  68752. * @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)
  68753. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  68754. */
  68755. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  68756. if (noMipmap === void 0) { noMipmap = false; }
  68757. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68758. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68759. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68760. if (onLoad === void 0) { onLoad = null; }
  68761. if (onError === void 0) { onError = null; }
  68762. var _this = _super.call(this, scene) || this;
  68763. _this._useInGammaSpace = false;
  68764. _this._generateHarmonics = true;
  68765. _this._isBABYLONPreprocessed = false;
  68766. _this._onLoad = null;
  68767. _this._onError = null;
  68768. /**
  68769. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  68770. */
  68771. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  68772. /**
  68773. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  68774. * This is usefull at run time to apply the good shader.
  68775. */
  68776. _this.isPMREM = false;
  68777. _this._isBlocking = true;
  68778. if (!url) {
  68779. return _this;
  68780. }
  68781. _this.name = url;
  68782. _this.url = url;
  68783. _this.hasAlpha = false;
  68784. _this.isCube = true;
  68785. _this._textureMatrix = BABYLON.Matrix.Identity();
  68786. _this._onLoad = onLoad;
  68787. _this._onError = onError;
  68788. _this.gammaSpace = false;
  68789. var caps = scene.getEngine().getCaps();
  68790. if (size) {
  68791. _this._isBABYLONPreprocessed = false;
  68792. _this._noMipmap = noMipmap;
  68793. _this._size = size;
  68794. _this._useInGammaSpace = useInGammaSpace;
  68795. _this._usePMREMGenerator = usePMREMGenerator &&
  68796. caps.textureLOD &&
  68797. caps.textureFloat &&
  68798. !_this._useInGammaSpace;
  68799. }
  68800. else {
  68801. _this._isBABYLONPreprocessed = true;
  68802. _this._noMipmap = false;
  68803. _this._useInGammaSpace = false;
  68804. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  68805. !_this._useInGammaSpace;
  68806. }
  68807. _this.isPMREM = _this._usePMREMGenerator;
  68808. _this._texture = _this._getFromCache(url, _this._noMipmap);
  68809. if (!_this._texture) {
  68810. if (!scene.useDelayedTextureLoading) {
  68811. _this.loadTexture();
  68812. }
  68813. else {
  68814. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  68815. }
  68816. }
  68817. return _this;
  68818. }
  68819. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  68820. /**
  68821. * Gets wether or not the texture is blocking during loading.
  68822. */
  68823. get: function () {
  68824. return this._isBlocking;
  68825. },
  68826. /**
  68827. * Sets wether or not the texture is blocking during loading.
  68828. */
  68829. set: function (value) {
  68830. this._isBlocking = value;
  68831. },
  68832. enumerable: true,
  68833. configurable: true
  68834. });
  68835. /**
  68836. * Occurs when the file is a preprocessed .babylon.hdr file.
  68837. */
  68838. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  68839. var _this = this;
  68840. var mipLevels = 0;
  68841. var floatArrayView = null;
  68842. var scene = this.getScene();
  68843. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  68844. var mips = new Array();
  68845. if (!floatArrayView) {
  68846. return mips;
  68847. }
  68848. var startIndex = 30;
  68849. for (var level = 0; level < mipLevels; level++) {
  68850. mips.push([]);
  68851. // Fill each pixel of the mip level.
  68852. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  68853. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68854. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  68855. mips[level].push(faceData);
  68856. startIndex += faceSize;
  68857. }
  68858. }
  68859. return mips;
  68860. } : null;
  68861. var callback = function (buffer) {
  68862. var scene = _this.getScene();
  68863. if (!scene) {
  68864. return null;
  68865. }
  68866. // Create Native Array Views
  68867. var intArrayView = new Int32Array(buffer);
  68868. floatArrayView = new Float32Array(buffer);
  68869. // Fill header.
  68870. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  68871. _this._size = intArrayView[1]; // CubeMap max mip face size.
  68872. // Update Texture Information.
  68873. if (!_this._texture) {
  68874. return null;
  68875. }
  68876. _this._texture.updateSize(_this._size, _this._size);
  68877. // Fill polynomial information.
  68878. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  68879. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  68880. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  68881. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  68882. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  68883. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  68884. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  68885. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  68886. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  68887. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  68888. _this.sphericalPolynomial = sphericalPolynomial;
  68889. // Fill pixel data.
  68890. mipLevels = intArrayView[29]; // Number of mip levels.
  68891. var startIndex = 30;
  68892. var data = [];
  68893. var faceSize = Math.pow(_this._size, 2) * 3;
  68894. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68895. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  68896. startIndex += faceSize;
  68897. }
  68898. var results = [];
  68899. var byteArray = null;
  68900. // Push each faces.
  68901. for (var k = 0; k < 6; k++) {
  68902. var dataFace = null;
  68903. // To be deprecated.
  68904. if (version === 1) {
  68905. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  68906. dataFace = data[j];
  68907. }
  68908. // If special cases.
  68909. if (!mipmapGenerator && dataFace) {
  68910. if (!scene.getEngine().getCaps().textureFloat) {
  68911. // 3 channels of 1 bytes per pixel in bytes.
  68912. var byteBuffer = new ArrayBuffer(faceSize);
  68913. byteArray = new Uint8Array(byteBuffer);
  68914. }
  68915. for (var i = 0; i < _this._size * _this._size; i++) {
  68916. // Put in gamma space if requested.
  68917. if (_this._useInGammaSpace) {
  68918. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68919. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68920. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68921. }
  68922. // Convert to int texture for fallback.
  68923. if (byteArray) {
  68924. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68925. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68926. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68927. // May use luminance instead if the result is not accurate.
  68928. var max = Math.max(Math.max(r, g), b);
  68929. if (max > 255) {
  68930. var scale = 255 / max;
  68931. r *= scale;
  68932. g *= scale;
  68933. b *= scale;
  68934. }
  68935. byteArray[(i * 3) + 0] = r;
  68936. byteArray[(i * 3) + 1] = g;
  68937. byteArray[(i * 3) + 2] = b;
  68938. }
  68939. }
  68940. }
  68941. // Fill the array accordingly.
  68942. if (byteArray) {
  68943. results.push(byteArray);
  68944. }
  68945. else {
  68946. results.push(dataFace);
  68947. }
  68948. }
  68949. return results;
  68950. };
  68951. if (scene) {
  68952. 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);
  68953. }
  68954. };
  68955. /**
  68956. * Occurs when the file is raw .hdr file.
  68957. */
  68958. HDRCubeTexture.prototype.loadHDRTexture = function () {
  68959. var _this = this;
  68960. var callback = function (buffer) {
  68961. var scene = _this.getScene();
  68962. if (!scene) {
  68963. return null;
  68964. }
  68965. // Extract the raw linear data.
  68966. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  68967. // Generate harmonics if needed.
  68968. if (_this._generateHarmonics) {
  68969. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  68970. _this.sphericalPolynomial = sphericalPolynomial;
  68971. }
  68972. var results = [];
  68973. var byteArray = null;
  68974. // Push each faces.
  68975. for (var j = 0; j < 6; j++) {
  68976. // Create uintarray fallback.
  68977. if (!scene.getEngine().getCaps().textureFloat) {
  68978. // 3 channels of 1 bytes per pixel in bytes.
  68979. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  68980. byteArray = new Uint8Array(byteBuffer);
  68981. }
  68982. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  68983. // If special cases.
  68984. if (_this._useInGammaSpace || byteArray) {
  68985. for (var i = 0; i < _this._size * _this._size; i++) {
  68986. // Put in gamma space if requested.
  68987. if (_this._useInGammaSpace) {
  68988. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68989. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68990. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68991. }
  68992. // Convert to int texture for fallback.
  68993. if (byteArray) {
  68994. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68995. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68996. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68997. // May use luminance instead if the result is not accurate.
  68998. var max = Math.max(Math.max(r, g), b);
  68999. if (max > 255) {
  69000. var scale = 255 / max;
  69001. r *= scale;
  69002. g *= scale;
  69003. b *= scale;
  69004. }
  69005. byteArray[(i * 3) + 0] = r;
  69006. byteArray[(i * 3) + 1] = g;
  69007. byteArray[(i * 3) + 2] = b;
  69008. }
  69009. }
  69010. }
  69011. if (byteArray) {
  69012. results.push(byteArray);
  69013. }
  69014. else {
  69015. results.push(dataFace);
  69016. }
  69017. }
  69018. return results;
  69019. };
  69020. var mipmapGenerator = null;
  69021. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  69022. // if (!this._noMipmap &&
  69023. // this._usePMREMGenerator) {
  69024. // mipmapGenerator = (data: ArrayBufferView[]) => {
  69025. // // Custom setup of the generator matching with the PBR shader values.
  69026. // var generator = new BABYLON.PMREMGenerator(data,
  69027. // this._size,
  69028. // this._size,
  69029. // 0,
  69030. // 3,
  69031. // this.getScene().getEngine().getCaps().textureFloat,
  69032. // 2048,
  69033. // 0.25,
  69034. // false,
  69035. // true);
  69036. // return generator.filterCubeMap();
  69037. // };
  69038. // }
  69039. var scene = this.getScene();
  69040. if (scene) {
  69041. 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);
  69042. }
  69043. };
  69044. /**
  69045. * Starts the loading process of the texture.
  69046. */
  69047. HDRCubeTexture.prototype.loadTexture = function () {
  69048. if (this._isBABYLONPreprocessed) {
  69049. this.loadBabylonTexture();
  69050. }
  69051. else {
  69052. this.loadHDRTexture();
  69053. }
  69054. };
  69055. HDRCubeTexture.prototype.clone = function () {
  69056. var scene = this.getScene();
  69057. if (!scene) {
  69058. return this;
  69059. }
  69060. var size = (this._isBABYLONPreprocessed ? null : this._size);
  69061. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  69062. // Base texture
  69063. newTexture.level = this.level;
  69064. newTexture.wrapU = this.wrapU;
  69065. newTexture.wrapV = this.wrapV;
  69066. newTexture.coordinatesIndex = this.coordinatesIndex;
  69067. newTexture.coordinatesMode = this.coordinatesMode;
  69068. return newTexture;
  69069. };
  69070. // Methods
  69071. HDRCubeTexture.prototype.delayLoad = function () {
  69072. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69073. return;
  69074. }
  69075. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69076. this._texture = this._getFromCache(this.url, this._noMipmap);
  69077. if (!this._texture) {
  69078. this.loadTexture();
  69079. }
  69080. };
  69081. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  69082. return this._textureMatrix;
  69083. };
  69084. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69085. this._textureMatrix = value;
  69086. };
  69087. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69088. var texture = null;
  69089. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  69090. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  69091. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  69092. texture.name = parsedTexture.name;
  69093. texture.hasAlpha = parsedTexture.hasAlpha;
  69094. texture.level = parsedTexture.level;
  69095. texture.coordinatesMode = parsedTexture.coordinatesMode;
  69096. texture.isBlocking = parsedTexture.isBlocking;
  69097. }
  69098. return texture;
  69099. };
  69100. HDRCubeTexture.prototype.serialize = function () {
  69101. if (!this.name) {
  69102. return null;
  69103. }
  69104. var serializationObject = {};
  69105. serializationObject.name = this.name;
  69106. serializationObject.hasAlpha = this.hasAlpha;
  69107. serializationObject.isCube = true;
  69108. serializationObject.level = this.level;
  69109. serializationObject.size = this._size;
  69110. serializationObject.coordinatesMode = this.coordinatesMode;
  69111. serializationObject.useInGammaSpace = this._useInGammaSpace;
  69112. serializationObject.generateHarmonics = this._generateHarmonics;
  69113. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  69114. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  69115. serializationObject.customType = "BABYLON.HDRCubeTexture";
  69116. serializationObject.noMipmap = this._noMipmap;
  69117. serializationObject.isBlocking = this._isBlocking;
  69118. return serializationObject;
  69119. };
  69120. /**
  69121. * Saves as a file the data contained in the texture in a binary format.
  69122. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69123. * as the spherical used in the lighting.
  69124. * @param url The HDR file url.
  69125. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69126. * @param onError Method called if any error happens during download.
  69127. * @return The packed binary data.
  69128. */
  69129. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  69130. if (onError === void 0) { onError = null; }
  69131. var callback = function (buffer) {
  69132. var data = new Blob([buffer], { type: 'application/octet-stream' });
  69133. // Returns a URL you can use as a href.
  69134. var objUrl = window.URL.createObjectURL(data);
  69135. // Simulates a link to it and click to dowload.
  69136. var a = document.createElement("a");
  69137. document.body.appendChild(a);
  69138. a.style.display = "none";
  69139. a.href = objUrl;
  69140. a.download = "envmap.babylon.hdr";
  69141. a.click();
  69142. };
  69143. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  69144. };
  69145. /**
  69146. * Serializes the data contained in the texture in a binary format.
  69147. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  69148. * as the spherical used in the lighting.
  69149. * @param url The HDR file url.
  69150. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  69151. * @param onError Method called if any error happens during download.
  69152. * @return The packed binary data.
  69153. */
  69154. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  69155. if (onError === void 0) { onError = null; }
  69156. // Needs the url tho create the texture.
  69157. if (!url) {
  69158. return;
  69159. }
  69160. // Check Power of two size.
  69161. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  69162. return;
  69163. }
  69164. // Coming Back in 3.x.
  69165. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  69166. };
  69167. HDRCubeTexture._facesMapping = [
  69168. "right",
  69169. "left",
  69170. "up",
  69171. "down",
  69172. "front",
  69173. "back"
  69174. ];
  69175. return HDRCubeTexture;
  69176. }(BABYLON.BaseTexture));
  69177. BABYLON.HDRCubeTexture = HDRCubeTexture;
  69178. })(BABYLON || (BABYLON = {}));
  69179. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  69180. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  69181. // Huge respect for a such great lib.
  69182. // Earcut license:
  69183. // Copyright (c) 2016, Mapbox
  69184. //
  69185. // Permission to use, copy, modify, and/or distribute this software for any purpose
  69186. // with or without fee is hereby granted, provided that the above copyright notice
  69187. // and this permission notice appear in all copies.
  69188. //
  69189. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  69190. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  69191. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  69192. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  69193. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  69194. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  69195. // THIS SOFTWARE.
  69196. var Earcut;
  69197. (function (Earcut) {
  69198. /**
  69199. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  69200. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  69201. * @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).
  69202. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  69203. */
  69204. function earcut(data, holeIndices, dim) {
  69205. dim = dim || 2;
  69206. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  69207. if (!outerNode)
  69208. return triangles;
  69209. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  69210. if (hasHoles)
  69211. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  69212. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  69213. if (data.length > 80 * dim) {
  69214. minX = maxX = data[0];
  69215. minY = maxY = data[1];
  69216. for (var i = dim; i < outerLen; i += dim) {
  69217. x = data[i];
  69218. y = data[i + 1];
  69219. if (x < minX)
  69220. minX = x;
  69221. if (y < minY)
  69222. minY = y;
  69223. if (x > maxX)
  69224. maxX = x;
  69225. if (y > maxY)
  69226. maxY = y;
  69227. }
  69228. // minX, minY and size are later used to transform coords into integers for z-order calculation
  69229. size = Math.max(maxX - minX, maxY - minY);
  69230. }
  69231. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  69232. return triangles;
  69233. }
  69234. Earcut.earcut = earcut;
  69235. var Node = /** @class */ (function () {
  69236. function Node(i, x, y) {
  69237. this.i = i;
  69238. this.x = x;
  69239. this.y = y;
  69240. this.prev = null;
  69241. this.next = null;
  69242. this.z = null;
  69243. this.prevZ = null;
  69244. this.nextZ = null;
  69245. this.steiner = false;
  69246. }
  69247. return Node;
  69248. }());
  69249. // create a circular doubly linked list from polygon points in the specified winding order
  69250. function linkedList(data, start, end, dim, clockwise) {
  69251. var i, last = null;
  69252. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  69253. for (i = start; i < end; i += dim)
  69254. last = insertNode(i, data[i], data[i + 1], last);
  69255. }
  69256. else {
  69257. for (i = end - dim; i >= start; i -= dim)
  69258. last = insertNode(i, data[i], data[i + 1], last);
  69259. }
  69260. if (last && equals(last, last.next)) {
  69261. removeNode(last);
  69262. last = last.next;
  69263. }
  69264. return last;
  69265. }
  69266. // eliminate colinear or duplicate points
  69267. function filterPoints(start, end) {
  69268. if (!start)
  69269. return start;
  69270. if (!end)
  69271. end = start;
  69272. var p = start, again;
  69273. do {
  69274. again = false;
  69275. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  69276. removeNode(p);
  69277. p = end = p.prev;
  69278. if (p === p.next)
  69279. return undefined;
  69280. again = true;
  69281. }
  69282. else {
  69283. p = p.next;
  69284. }
  69285. } while (again || p !== end);
  69286. return end;
  69287. }
  69288. // main ear slicing loop which triangulates a polygon (given as a linked list)
  69289. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  69290. if (!ear)
  69291. return;
  69292. // interlink polygon nodes in z-order
  69293. if (!pass && size)
  69294. indexCurve(ear, minX, minY, size);
  69295. var stop = ear, prev, next;
  69296. // iterate through ears, slicing them one by one
  69297. while (ear.prev !== ear.next) {
  69298. prev = ear.prev;
  69299. next = ear.next;
  69300. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  69301. // cut off the triangle
  69302. triangles.push(prev.i / dim);
  69303. triangles.push(ear.i / dim);
  69304. triangles.push(next.i / dim);
  69305. removeNode(ear);
  69306. // skipping the next vertice leads to less sliver triangles
  69307. ear = next.next;
  69308. stop = next.next;
  69309. continue;
  69310. }
  69311. ear = next;
  69312. // if we looped through the whole remaining polygon and can't find any more ears
  69313. if (ear === stop) {
  69314. // try filtering points and slicing again
  69315. if (!pass) {
  69316. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  69317. // if this didn't work, try curing all small self-intersections locally
  69318. }
  69319. else if (pass === 1) {
  69320. ear = cureLocalIntersections(ear, triangles, dim);
  69321. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  69322. // as a last resort, try splitting the remaining polygon into two
  69323. }
  69324. else if (pass === 2) {
  69325. splitEarcut(ear, triangles, dim, minX, minY, size);
  69326. }
  69327. break;
  69328. }
  69329. }
  69330. }
  69331. // check whether a polygon node forms a valid ear with adjacent nodes
  69332. function isEar(ear) {
  69333. var a = ear.prev, b = ear, c = ear.next;
  69334. if (area(a, b, c) >= 0)
  69335. return false; // reflex, can't be an ear
  69336. // now make sure we don't have other points inside the potential ear
  69337. var p = ear.next.next;
  69338. while (p !== ear.prev) {
  69339. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69340. area(p.prev, p, p.next) >= 0)
  69341. return false;
  69342. p = p.next;
  69343. }
  69344. return true;
  69345. }
  69346. function isEarHashed(ear, minX, minY, size) {
  69347. var a = ear.prev, b = ear, c = ear.next;
  69348. if (area(a, b, c) >= 0)
  69349. return false; // reflex, can't be an ear
  69350. // triangle bbox; min & max are calculated like this for speed
  69351. 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);
  69352. // z-order range for the current triangle bbox;
  69353. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  69354. // first look for points inside the triangle in increasing z-order
  69355. var p = ear.nextZ;
  69356. while (p && p.z <= maxZ) {
  69357. if (p !== ear.prev &&
  69358. p !== ear.next &&
  69359. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69360. area(p.prev, p, p.next) >= 0)
  69361. return false;
  69362. p = p.nextZ;
  69363. }
  69364. // then look for points in decreasing z-order
  69365. p = ear.prevZ;
  69366. while (p && p.z >= minZ) {
  69367. if (p !== ear.prev &&
  69368. p !== ear.next &&
  69369. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  69370. area(p.prev, p, p.next) >= 0)
  69371. return false;
  69372. p = p.prevZ;
  69373. }
  69374. return true;
  69375. }
  69376. // go through all polygon nodes and cure small local self-intersections
  69377. function cureLocalIntersections(start, triangles, dim) {
  69378. var p = start;
  69379. do {
  69380. var a = p.prev, b = p.next.next;
  69381. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  69382. triangles.push(a.i / dim);
  69383. triangles.push(p.i / dim);
  69384. triangles.push(b.i / dim);
  69385. // remove two nodes involved
  69386. removeNode(p);
  69387. removeNode(p.next);
  69388. p = start = b;
  69389. }
  69390. p = p.next;
  69391. } while (p !== start);
  69392. return p;
  69393. }
  69394. // try splitting polygon into two and triangulate them independently
  69395. function splitEarcut(start, triangles, dim, minX, minY, size) {
  69396. // look for a valid diagonal that divides the polygon into two
  69397. var a = start;
  69398. do {
  69399. var b = a.next.next;
  69400. while (b !== a.prev) {
  69401. if (a.i !== b.i && isValidDiagonal(a, b)) {
  69402. // split the polygon in two by the diagonal
  69403. var c = splitPolygon(a, b);
  69404. // filter colinear points around the cuts
  69405. a = filterPoints(a, a.next);
  69406. c = filterPoints(c, c.next);
  69407. // run earcut on each half
  69408. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  69409. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  69410. return;
  69411. }
  69412. b = b.next;
  69413. }
  69414. a = a.next;
  69415. } while (a !== start);
  69416. }
  69417. // link every hole into the outer loop, producing a single-ring polygon without holes
  69418. function eliminateHoles(data, holeIndices, outerNode, dim) {
  69419. var queue = [], i, len, start, end, list;
  69420. for (i = 0, len = holeIndices.length; i < len; i++) {
  69421. start = holeIndices[i] * dim;
  69422. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69423. list = linkedList(data, start, end, dim, false);
  69424. if (list === list.next)
  69425. list.steiner = true;
  69426. queue.push(getLeftmost(list));
  69427. }
  69428. queue.sort(compareX);
  69429. // process holes from left to right
  69430. for (i = 0; i < queue.length; i++) {
  69431. eliminateHole(queue[i], outerNode);
  69432. outerNode = filterPoints(outerNode, outerNode.next);
  69433. }
  69434. return outerNode;
  69435. }
  69436. function compareX(a, b) {
  69437. return a.x - b.x;
  69438. }
  69439. // find a bridge between vertices that connects hole with an outer ring and and link it
  69440. function eliminateHole(hole, outerNode) {
  69441. outerNode = findHoleBridge(hole, outerNode);
  69442. if (outerNode) {
  69443. var b = splitPolygon(outerNode, hole);
  69444. filterPoints(b, b.next);
  69445. }
  69446. }
  69447. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  69448. function findHoleBridge(hole, outerNode) {
  69449. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  69450. // find a segment intersected by a ray from the hole's leftmost point to the left;
  69451. // segment's endpoint with lesser x will be potential connection point
  69452. do {
  69453. if (hy <= p.y && hy >= p.next.y) {
  69454. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  69455. if (x <= hx && x > qx) {
  69456. qx = x;
  69457. if (x === hx) {
  69458. if (hy === p.y)
  69459. return p;
  69460. if (hy === p.next.y)
  69461. return p.next;
  69462. }
  69463. m = p.x < p.next.x ? p : p.next;
  69464. }
  69465. }
  69466. p = p.next;
  69467. } while (p !== outerNode);
  69468. if (!m)
  69469. return null;
  69470. if (hx === qx)
  69471. return m.prev; // hole touches outer segment; pick lower endpoint
  69472. // look for points inside the triangle of hole point, segment intersection and endpoint;
  69473. // if there are no points found, we have a valid connection;
  69474. // otherwise choose the point of the minimum angle with the ray as connection point
  69475. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  69476. p = m.next;
  69477. while (p !== stop) {
  69478. if (hx >= p.x &&
  69479. p.x >= mx &&
  69480. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  69481. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  69482. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  69483. m = p;
  69484. tanMin = tan;
  69485. }
  69486. }
  69487. p = p.next;
  69488. }
  69489. return m;
  69490. }
  69491. // interlink polygon nodes in z-order
  69492. function indexCurve(start, minX, minY, size) {
  69493. var p = start;
  69494. do {
  69495. if (p.z === null)
  69496. p.z = zOrder(p.x, p.y, minX, minY, size);
  69497. p.prevZ = p.prev;
  69498. p.nextZ = p.next;
  69499. p = p.next;
  69500. } while (p !== start);
  69501. p.prevZ.nextZ = null;
  69502. p.prevZ = null;
  69503. sortLinked(p);
  69504. }
  69505. // Simon Tatham's linked list merge sort algorithm
  69506. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  69507. function sortLinked(list) {
  69508. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  69509. do {
  69510. p = list;
  69511. list = null;
  69512. tail = null;
  69513. numMerges = 0;
  69514. while (p) {
  69515. numMerges++;
  69516. q = p;
  69517. pSize = 0;
  69518. for (i = 0; i < inSize; i++) {
  69519. pSize++;
  69520. q = q.nextZ;
  69521. if (!q)
  69522. break;
  69523. }
  69524. qSize = inSize;
  69525. while (pSize > 0 || (qSize > 0 && q)) {
  69526. if (pSize === 0) {
  69527. e = q;
  69528. q = q.nextZ;
  69529. qSize--;
  69530. }
  69531. else if (qSize === 0 || !q) {
  69532. e = p;
  69533. p = p.nextZ;
  69534. pSize--;
  69535. }
  69536. else if (p.z <= q.z) {
  69537. e = p;
  69538. p = p.nextZ;
  69539. pSize--;
  69540. }
  69541. else {
  69542. e = q;
  69543. q = q.nextZ;
  69544. qSize--;
  69545. }
  69546. if (tail)
  69547. tail.nextZ = e;
  69548. else
  69549. list = e;
  69550. e.prevZ = tail;
  69551. tail = e;
  69552. }
  69553. p = q;
  69554. }
  69555. tail.nextZ = null;
  69556. inSize *= 2;
  69557. } while (numMerges > 1);
  69558. return list;
  69559. }
  69560. // z-order of a point given coords and size of the data bounding box
  69561. function zOrder(x, y, minX, minY, size) {
  69562. // coords are transformed into non-negative 15-bit integer range
  69563. x = 32767 * (x - minX) / size;
  69564. y = 32767 * (y - minY) / size;
  69565. x = (x | (x << 8)) & 0x00FF00FF;
  69566. x = (x | (x << 4)) & 0x0F0F0F0F;
  69567. x = (x | (x << 2)) & 0x33333333;
  69568. x = (x | (x << 1)) & 0x55555555;
  69569. y = (y | (y << 8)) & 0x00FF00FF;
  69570. y = (y | (y << 4)) & 0x0F0F0F0F;
  69571. y = (y | (y << 2)) & 0x33333333;
  69572. y = (y | (y << 1)) & 0x55555555;
  69573. return x | (y << 1);
  69574. }
  69575. // find the leftmost node of a polygon ring
  69576. function getLeftmost(start) {
  69577. var p = start, leftmost = start;
  69578. do {
  69579. if (p.x < leftmost.x)
  69580. leftmost = p;
  69581. p = p.next;
  69582. } while (p !== start);
  69583. return leftmost;
  69584. }
  69585. // check if a point lies within a convex triangle
  69586. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  69587. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  69588. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  69589. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  69590. }
  69591. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  69592. function isValidDiagonal(a, b) {
  69593. return a.next.i !== b.i &&
  69594. a.prev.i !== b.i &&
  69595. !intersectsPolygon(a, b) &&
  69596. locallyInside(a, b) &&
  69597. locallyInside(b, a) &&
  69598. middleInside(a, b);
  69599. }
  69600. // signed area of a triangle
  69601. function area(p, q, r) {
  69602. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  69603. }
  69604. // check if two points are equal
  69605. function equals(p1, p2) {
  69606. return p1.x === p2.x && p1.y === p2.y;
  69607. }
  69608. // check if two segments intersect
  69609. function intersects(p1, q1, p2, q2) {
  69610. if ((equals(p1, q1) && equals(p2, q2)) ||
  69611. (equals(p1, q2) && equals(p2, q1)))
  69612. return true;
  69613. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  69614. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  69615. }
  69616. // check if a polygon diagonal intersects any polygon segments
  69617. function intersectsPolygon(a, b) {
  69618. var p = a;
  69619. do {
  69620. if (p.i !== a.i &&
  69621. p.next.i !== a.i &&
  69622. p.i !== b.i &&
  69623. p.next.i !== b.i &&
  69624. intersects(p, p.next, a, b))
  69625. return true;
  69626. p = p.next;
  69627. } while (p !== a);
  69628. return false;
  69629. }
  69630. // check if a polygon diagonal is locally inside the polygon
  69631. function locallyInside(a, b) {
  69632. return area(a.prev, a, a.next) < 0
  69633. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  69634. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  69635. }
  69636. // check if the middle point of a polygon diagonal is inside the polygon
  69637. function middleInside(a, b) {
  69638. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  69639. do {
  69640. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  69641. inside = !inside;
  69642. p = p.next;
  69643. } while (p !== a);
  69644. return inside;
  69645. }
  69646. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  69647. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  69648. function splitPolygon(a, b) {
  69649. 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;
  69650. a.next = b;
  69651. b.prev = a;
  69652. a2.next = an;
  69653. an.prev = a2;
  69654. b2.next = a2;
  69655. a2.prev = b2;
  69656. bp.next = b2;
  69657. b2.prev = bp;
  69658. return b2;
  69659. }
  69660. // create a node and optionally link it with previous one (in a circular doubly linked list)
  69661. function insertNode(i, x, y, last) {
  69662. var p = new Node(i, x, y);
  69663. if (!last) {
  69664. p.prev = p;
  69665. p.next = p;
  69666. }
  69667. else {
  69668. p.next = last.next;
  69669. p.prev = last;
  69670. last.next.prev = p;
  69671. last.next = p;
  69672. }
  69673. return p;
  69674. }
  69675. function removeNode(p) {
  69676. p.next.prev = p.prev;
  69677. p.prev.next = p.next;
  69678. if (p.prevZ)
  69679. p.prevZ.nextZ = p.nextZ;
  69680. if (p.nextZ)
  69681. p.nextZ.prevZ = p.prevZ;
  69682. }
  69683. /**
  69684. * return a percentage difference between the polygon area and its triangulation area;
  69685. * used to verify correctness of triangulation
  69686. */
  69687. function deviation(data, holeIndices, dim, triangles) {
  69688. var hasHoles = holeIndices && holeIndices.length;
  69689. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  69690. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  69691. if (hasHoles) {
  69692. for (var i = 0, len = holeIndices.length; i < len; i++) {
  69693. var start = holeIndices[i] * dim;
  69694. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69695. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  69696. }
  69697. }
  69698. var trianglesArea = 0;
  69699. for (i = 0; i < triangles.length; i += 3) {
  69700. var a = triangles[i] * dim;
  69701. var b = triangles[i + 1] * dim;
  69702. var c = triangles[i + 2] * dim;
  69703. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  69704. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  69705. }
  69706. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  69707. }
  69708. Earcut.deviation = deviation;
  69709. ;
  69710. function signedArea(data, start, end, dim) {
  69711. var sum = 0;
  69712. for (var i = start, j = end - dim; i < end; i += dim) {
  69713. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  69714. j = i;
  69715. }
  69716. return sum;
  69717. }
  69718. /**
  69719. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  69720. */
  69721. function flatten(data) {
  69722. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  69723. for (var i = 0; i < data.length; i++) {
  69724. for (var j = 0; j < data[i].length; j++) {
  69725. for (var d = 0; d < dim; d++)
  69726. result.vertices.push(data[i][j][d]);
  69727. }
  69728. if (i > 0) {
  69729. holeIndex += data[i - 1].length;
  69730. result.holes.push(holeIndex);
  69731. }
  69732. }
  69733. return result;
  69734. }
  69735. Earcut.flatten = flatten;
  69736. ;
  69737. })(Earcut || (Earcut = {}));
  69738. //# sourceMappingURL=babylon.earcut.js.map
  69739. var BABYLON;
  69740. (function (BABYLON) {
  69741. var IndexedVector2 = /** @class */ (function (_super) {
  69742. __extends(IndexedVector2, _super);
  69743. function IndexedVector2(original, index) {
  69744. var _this = _super.call(this, original.x, original.y) || this;
  69745. _this.index = index;
  69746. return _this;
  69747. }
  69748. return IndexedVector2;
  69749. }(BABYLON.Vector2));
  69750. var PolygonPoints = /** @class */ (function () {
  69751. function PolygonPoints() {
  69752. this.elements = new Array();
  69753. }
  69754. PolygonPoints.prototype.add = function (originalPoints) {
  69755. var _this = this;
  69756. var result = new Array();
  69757. originalPoints.forEach(function (point) {
  69758. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  69759. var newPoint = new IndexedVector2(point, _this.elements.length);
  69760. result.push(newPoint);
  69761. _this.elements.push(newPoint);
  69762. }
  69763. });
  69764. return result;
  69765. };
  69766. PolygonPoints.prototype.computeBounds = function () {
  69767. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  69768. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  69769. this.elements.forEach(function (point) {
  69770. // x
  69771. if (point.x < lmin.x) {
  69772. lmin.x = point.x;
  69773. }
  69774. else if (point.x > lmax.x) {
  69775. lmax.x = point.x;
  69776. }
  69777. // y
  69778. if (point.y < lmin.y) {
  69779. lmin.y = point.y;
  69780. }
  69781. else if (point.y > lmax.y) {
  69782. lmax.y = point.y;
  69783. }
  69784. });
  69785. return {
  69786. min: lmin,
  69787. max: lmax,
  69788. width: lmax.x - lmin.x,
  69789. height: lmax.y - lmin.y
  69790. };
  69791. };
  69792. return PolygonPoints;
  69793. }());
  69794. var Polygon = /** @class */ (function () {
  69795. function Polygon() {
  69796. }
  69797. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  69798. return [
  69799. new BABYLON.Vector2(xmin, ymin),
  69800. new BABYLON.Vector2(xmax, ymin),
  69801. new BABYLON.Vector2(xmax, ymax),
  69802. new BABYLON.Vector2(xmin, ymax)
  69803. ];
  69804. };
  69805. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  69806. if (cx === void 0) { cx = 0; }
  69807. if (cy === void 0) { cy = 0; }
  69808. if (numberOfSides === void 0) { numberOfSides = 32; }
  69809. var result = new Array();
  69810. var angle = 0;
  69811. var increment = (Math.PI * 2) / numberOfSides;
  69812. for (var i = 0; i < numberOfSides; i++) {
  69813. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  69814. angle -= increment;
  69815. }
  69816. return result;
  69817. };
  69818. Polygon.Parse = function (input) {
  69819. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  69820. var i, result = [];
  69821. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  69822. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  69823. }
  69824. return result;
  69825. };
  69826. Polygon.StartingAt = function (x, y) {
  69827. return BABYLON.Path2.StartingAt(x, y);
  69828. };
  69829. return Polygon;
  69830. }());
  69831. BABYLON.Polygon = Polygon;
  69832. var PolygonMeshBuilder = /** @class */ (function () {
  69833. function PolygonMeshBuilder(name, contours, scene) {
  69834. this._points = new PolygonPoints();
  69835. this._outlinepoints = new PolygonPoints();
  69836. this._holes = new Array();
  69837. this._epoints = new Array();
  69838. this._eholes = new Array();
  69839. this._name = name;
  69840. this._scene = scene;
  69841. var points;
  69842. if (contours instanceof BABYLON.Path2) {
  69843. points = contours.getPoints();
  69844. }
  69845. else {
  69846. points = contours;
  69847. }
  69848. this._addToepoint(points);
  69849. this._points.add(points);
  69850. this._outlinepoints.add(points);
  69851. }
  69852. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  69853. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  69854. var p = points_1[_i];
  69855. this._epoints.push(p.x, p.y);
  69856. }
  69857. };
  69858. PolygonMeshBuilder.prototype.addHole = function (hole) {
  69859. this._points.add(hole);
  69860. var holepoints = new PolygonPoints();
  69861. holepoints.add(hole);
  69862. this._holes.push(holepoints);
  69863. this._eholes.push(this._epoints.length / 2);
  69864. this._addToepoint(hole);
  69865. return this;
  69866. };
  69867. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  69868. var _this = this;
  69869. if (updatable === void 0) { updatable = false; }
  69870. if (depth === void 0) { depth = 0; }
  69871. var result = new BABYLON.Mesh(this._name, this._scene);
  69872. var normals = new Array();
  69873. var positions = new Array();
  69874. var uvs = new Array();
  69875. var bounds = this._points.computeBounds();
  69876. this._points.elements.forEach(function (p) {
  69877. normals.push(0, 1.0, 0);
  69878. positions.push(p.x, 0, p.y);
  69879. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  69880. });
  69881. var indices = new Array();
  69882. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  69883. for (var i = 0; i < res.length; i++) {
  69884. indices.push(res[i]);
  69885. }
  69886. if (depth > 0) {
  69887. var positionscount = (positions.length / 3); //get the current pointcount
  69888. this._points.elements.forEach(function (p) {
  69889. normals.push(0, -1.0, 0);
  69890. positions.push(p.x, -depth, p.y);
  69891. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  69892. });
  69893. var totalCount = indices.length;
  69894. for (var i = 0; i < totalCount; i += 3) {
  69895. var i0 = indices[i + 0];
  69896. var i1 = indices[i + 1];
  69897. var i2 = indices[i + 2];
  69898. indices.push(i2 + positionscount);
  69899. indices.push(i1 + positionscount);
  69900. indices.push(i0 + positionscount);
  69901. }
  69902. //Add the sides
  69903. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  69904. this._holes.forEach(function (hole) {
  69905. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  69906. });
  69907. }
  69908. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  69909. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  69910. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  69911. result.setIndices(indices);
  69912. return result;
  69913. };
  69914. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  69915. var StartIndex = positions.length / 3;
  69916. var ulength = 0;
  69917. for (var i = 0; i < points.elements.length; i++) {
  69918. var p = points.elements[i];
  69919. var p1;
  69920. if ((i + 1) > points.elements.length - 1) {
  69921. p1 = points.elements[0];
  69922. }
  69923. else {
  69924. p1 = points.elements[i + 1];
  69925. }
  69926. positions.push(p.x, 0, p.y);
  69927. positions.push(p.x, -depth, p.y);
  69928. positions.push(p1.x, 0, p1.y);
  69929. positions.push(p1.x, -depth, p1.y);
  69930. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  69931. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  69932. var v3 = v2.subtract(v1);
  69933. var v4 = new BABYLON.Vector3(0, 1, 0);
  69934. var vn = BABYLON.Vector3.Cross(v3, v4);
  69935. vn = vn.normalize();
  69936. uvs.push(ulength / bounds.width, 0);
  69937. uvs.push(ulength / bounds.width, 1);
  69938. ulength += v3.length();
  69939. uvs.push((ulength / bounds.width), 0);
  69940. uvs.push((ulength / bounds.width), 1);
  69941. if (!flip) {
  69942. normals.push(-vn.x, -vn.y, -vn.z);
  69943. normals.push(-vn.x, -vn.y, -vn.z);
  69944. normals.push(-vn.x, -vn.y, -vn.z);
  69945. normals.push(-vn.x, -vn.y, -vn.z);
  69946. indices.push(StartIndex);
  69947. indices.push(StartIndex + 1);
  69948. indices.push(StartIndex + 2);
  69949. indices.push(StartIndex + 1);
  69950. indices.push(StartIndex + 3);
  69951. indices.push(StartIndex + 2);
  69952. }
  69953. else {
  69954. normals.push(vn.x, vn.y, vn.z);
  69955. normals.push(vn.x, vn.y, vn.z);
  69956. normals.push(vn.x, vn.y, vn.z);
  69957. normals.push(vn.x, vn.y, vn.z);
  69958. indices.push(StartIndex);
  69959. indices.push(StartIndex + 2);
  69960. indices.push(StartIndex + 1);
  69961. indices.push(StartIndex + 1);
  69962. indices.push(StartIndex + 2);
  69963. indices.push(StartIndex + 3);
  69964. }
  69965. StartIndex += 4;
  69966. }
  69967. ;
  69968. };
  69969. return PolygonMeshBuilder;
  69970. }());
  69971. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  69972. })(BABYLON || (BABYLON = {}));
  69973. //# sourceMappingURL=babylon.polygonMesh.js.map
  69974. var BABYLON;
  69975. (function (BABYLON) {
  69976. // Unique ID when we import meshes from Babylon to CSG
  69977. var currentCSGMeshId = 0;
  69978. // # class Vertex
  69979. // Represents a vertex of a polygon. Use your own vertex class instead of this
  69980. // one to provide additional features like texture coordinates and vertex
  69981. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  69982. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  69983. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  69984. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  69985. // is not used anywhere else.
  69986. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  69987. var Vertex = /** @class */ (function () {
  69988. function Vertex(pos, normal, uv) {
  69989. this.pos = pos;
  69990. this.normal = normal;
  69991. this.uv = uv;
  69992. }
  69993. Vertex.prototype.clone = function () {
  69994. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  69995. };
  69996. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  69997. // orientation of a polygon is flipped.
  69998. Vertex.prototype.flip = function () {
  69999. this.normal = this.normal.scale(-1);
  70000. };
  70001. // Create a new vertex between this vertex and `other` by linearly
  70002. // interpolating all properties using a parameter of `t`. Subclasses should
  70003. // override this to interpolate additional properties.
  70004. Vertex.prototype.interpolate = function (other, t) {
  70005. 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));
  70006. };
  70007. return Vertex;
  70008. }());
  70009. // # class Plane
  70010. // Represents a plane in 3D space.
  70011. var Plane = /** @class */ (function () {
  70012. function Plane(normal, w) {
  70013. this.normal = normal;
  70014. this.w = w;
  70015. }
  70016. Plane.FromPoints = function (a, b, c) {
  70017. var v0 = c.subtract(a);
  70018. var v1 = b.subtract(a);
  70019. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  70020. return null;
  70021. }
  70022. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  70023. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  70024. };
  70025. Plane.prototype.clone = function () {
  70026. return new Plane(this.normal.clone(), this.w);
  70027. };
  70028. Plane.prototype.flip = function () {
  70029. this.normal.scaleInPlace(-1);
  70030. this.w = -this.w;
  70031. };
  70032. // Split `polygon` by this plane if needed, then put the polygon or polygon
  70033. // fragments in the appropriate lists. Coplanar polygons go into either
  70034. // `coplanarFront` or `coplanarBack` depending on their orientation with
  70035. // respect to this plane. Polygons in front or in back of this plane go into
  70036. // either `front` or `back`.
  70037. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  70038. var COPLANAR = 0;
  70039. var FRONT = 1;
  70040. var BACK = 2;
  70041. var SPANNING = 3;
  70042. // Classify each point as well as the entire polygon into one of the above
  70043. // four classes.
  70044. var polygonType = 0;
  70045. var types = [];
  70046. var i;
  70047. var t;
  70048. for (i = 0; i < polygon.vertices.length; i++) {
  70049. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  70050. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  70051. polygonType |= type;
  70052. types.push(type);
  70053. }
  70054. // Put the polygon in the correct list, splitting it when necessary.
  70055. switch (polygonType) {
  70056. case COPLANAR:
  70057. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  70058. break;
  70059. case FRONT:
  70060. front.push(polygon);
  70061. break;
  70062. case BACK:
  70063. back.push(polygon);
  70064. break;
  70065. case SPANNING:
  70066. var f = [], b = [];
  70067. for (i = 0; i < polygon.vertices.length; i++) {
  70068. var j = (i + 1) % polygon.vertices.length;
  70069. var ti = types[i], tj = types[j];
  70070. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  70071. if (ti !== BACK)
  70072. f.push(vi);
  70073. if (ti !== FRONT)
  70074. b.push(ti !== BACK ? vi.clone() : vi);
  70075. if ((ti | tj) === SPANNING) {
  70076. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  70077. var v = vi.interpolate(vj, t);
  70078. f.push(v);
  70079. b.push(v.clone());
  70080. }
  70081. }
  70082. var poly;
  70083. if (f.length >= 3) {
  70084. poly = new Polygon(f, polygon.shared);
  70085. if (poly.plane)
  70086. front.push(poly);
  70087. }
  70088. if (b.length >= 3) {
  70089. poly = new Polygon(b, polygon.shared);
  70090. if (poly.plane)
  70091. back.push(poly);
  70092. }
  70093. break;
  70094. }
  70095. };
  70096. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  70097. // point is on the plane.
  70098. Plane.EPSILON = 1e-5;
  70099. return Plane;
  70100. }());
  70101. // # class Polygon
  70102. // Represents a convex polygon. The vertices used to initialize a polygon must
  70103. // be coplanar and form a convex loop.
  70104. //
  70105. // Each convex polygon has a `shared` property, which is shared between all
  70106. // polygons that are clones of each other or were split from the same polygon.
  70107. // This can be used to define per-polygon properties (such as surface color).
  70108. var Polygon = /** @class */ (function () {
  70109. function Polygon(vertices, shared) {
  70110. this.vertices = vertices;
  70111. this.shared = shared;
  70112. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  70113. }
  70114. Polygon.prototype.clone = function () {
  70115. var vertices = this.vertices.map(function (v) { return v.clone(); });
  70116. return new Polygon(vertices, this.shared);
  70117. };
  70118. Polygon.prototype.flip = function () {
  70119. this.vertices.reverse().map(function (v) { v.flip(); });
  70120. this.plane.flip();
  70121. };
  70122. return Polygon;
  70123. }());
  70124. // # class Node
  70125. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  70126. // by picking a polygon to split along. That polygon (and all other coplanar
  70127. // polygons) are added directly to that node and the other polygons are added to
  70128. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  70129. // no distinction between internal and leaf nodes.
  70130. var Node = /** @class */ (function () {
  70131. function Node(polygons) {
  70132. this.plane = null;
  70133. this.front = null;
  70134. this.back = null;
  70135. this.polygons = new Array();
  70136. if (polygons) {
  70137. this.build(polygons);
  70138. }
  70139. }
  70140. Node.prototype.clone = function () {
  70141. var node = new Node();
  70142. node.plane = this.plane && this.plane.clone();
  70143. node.front = this.front && this.front.clone();
  70144. node.back = this.back && this.back.clone();
  70145. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  70146. return node;
  70147. };
  70148. // Convert solid space to empty space and empty space to solid space.
  70149. Node.prototype.invert = function () {
  70150. for (var i = 0; i < this.polygons.length; i++) {
  70151. this.polygons[i].flip();
  70152. }
  70153. if (this.plane) {
  70154. this.plane.flip();
  70155. }
  70156. if (this.front) {
  70157. this.front.invert();
  70158. }
  70159. if (this.back) {
  70160. this.back.invert();
  70161. }
  70162. var temp = this.front;
  70163. this.front = this.back;
  70164. this.back = temp;
  70165. };
  70166. // Recursively remove all polygons in `polygons` that are inside this BSP
  70167. // tree.
  70168. Node.prototype.clipPolygons = function (polygons) {
  70169. if (!this.plane)
  70170. return polygons.slice();
  70171. var front = new Array(), back = new Array();
  70172. for (var i = 0; i < polygons.length; i++) {
  70173. this.plane.splitPolygon(polygons[i], front, back, front, back);
  70174. }
  70175. if (this.front) {
  70176. front = this.front.clipPolygons(front);
  70177. }
  70178. if (this.back) {
  70179. back = this.back.clipPolygons(back);
  70180. }
  70181. else {
  70182. back = [];
  70183. }
  70184. return front.concat(back);
  70185. };
  70186. // Remove all polygons in this BSP tree that are inside the other BSP tree
  70187. // `bsp`.
  70188. Node.prototype.clipTo = function (bsp) {
  70189. this.polygons = bsp.clipPolygons(this.polygons);
  70190. if (this.front)
  70191. this.front.clipTo(bsp);
  70192. if (this.back)
  70193. this.back.clipTo(bsp);
  70194. };
  70195. // Return a list of all polygons in this BSP tree.
  70196. Node.prototype.allPolygons = function () {
  70197. var polygons = this.polygons.slice();
  70198. if (this.front)
  70199. polygons = polygons.concat(this.front.allPolygons());
  70200. if (this.back)
  70201. polygons = polygons.concat(this.back.allPolygons());
  70202. return polygons;
  70203. };
  70204. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  70205. // new polygons are filtered down to the bottom of the tree and become new
  70206. // nodes there. Each set of polygons is partitioned using the first polygon
  70207. // (no heuristic is used to pick a good split).
  70208. Node.prototype.build = function (polygons) {
  70209. if (!polygons.length)
  70210. return;
  70211. if (!this.plane)
  70212. this.plane = polygons[0].plane.clone();
  70213. var front = new Array(), back = new Array();
  70214. for (var i = 0; i < polygons.length; i++) {
  70215. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  70216. }
  70217. if (front.length) {
  70218. if (!this.front)
  70219. this.front = new Node();
  70220. this.front.build(front);
  70221. }
  70222. if (back.length) {
  70223. if (!this.back)
  70224. this.back = new Node();
  70225. this.back.build(back);
  70226. }
  70227. };
  70228. return Node;
  70229. }());
  70230. var CSG = /** @class */ (function () {
  70231. function CSG() {
  70232. this.polygons = new Array();
  70233. }
  70234. // Convert BABYLON.Mesh to BABYLON.CSG
  70235. CSG.FromMesh = function (mesh) {
  70236. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  70237. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  70238. if (mesh instanceof BABYLON.Mesh) {
  70239. mesh.computeWorldMatrix(true);
  70240. matrix = mesh.getWorldMatrix();
  70241. meshPosition = mesh.position.clone();
  70242. meshRotation = mesh.rotation.clone();
  70243. if (mesh.rotationQuaternion) {
  70244. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  70245. }
  70246. meshScaling = mesh.scaling.clone();
  70247. }
  70248. else {
  70249. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  70250. }
  70251. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70252. var subMeshes = mesh.subMeshes;
  70253. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  70254. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  70255. vertices = [];
  70256. for (var j = 0; j < 3; j++) {
  70257. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  70258. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  70259. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  70260. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  70261. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  70262. vertex = new Vertex(position, normal, uv);
  70263. vertices.push(vertex);
  70264. }
  70265. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  70266. // To handle the case of degenerated triangle
  70267. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  70268. if (polygon.plane)
  70269. polygons.push(polygon);
  70270. }
  70271. }
  70272. var csg = CSG.FromPolygons(polygons);
  70273. csg.matrix = matrix;
  70274. csg.position = meshPosition;
  70275. csg.rotation = meshRotation;
  70276. csg.scaling = meshScaling;
  70277. csg.rotationQuaternion = meshRotationQuaternion;
  70278. currentCSGMeshId++;
  70279. return csg;
  70280. };
  70281. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  70282. CSG.FromPolygons = function (polygons) {
  70283. var csg = new CSG();
  70284. csg.polygons = polygons;
  70285. return csg;
  70286. };
  70287. CSG.prototype.clone = function () {
  70288. var csg = new CSG();
  70289. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  70290. csg.copyTransformAttributes(this);
  70291. return csg;
  70292. };
  70293. CSG.prototype.union = function (csg) {
  70294. var a = new Node(this.clone().polygons);
  70295. var b = new Node(csg.clone().polygons);
  70296. a.clipTo(b);
  70297. b.clipTo(a);
  70298. b.invert();
  70299. b.clipTo(a);
  70300. b.invert();
  70301. a.build(b.allPolygons());
  70302. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70303. };
  70304. CSG.prototype.unionInPlace = function (csg) {
  70305. var a = new Node(this.polygons);
  70306. var b = new Node(csg.polygons);
  70307. a.clipTo(b);
  70308. b.clipTo(a);
  70309. b.invert();
  70310. b.clipTo(a);
  70311. b.invert();
  70312. a.build(b.allPolygons());
  70313. this.polygons = a.allPolygons();
  70314. };
  70315. CSG.prototype.subtract = function (csg) {
  70316. var a = new Node(this.clone().polygons);
  70317. var b = new Node(csg.clone().polygons);
  70318. a.invert();
  70319. a.clipTo(b);
  70320. b.clipTo(a);
  70321. b.invert();
  70322. b.clipTo(a);
  70323. b.invert();
  70324. a.build(b.allPolygons());
  70325. a.invert();
  70326. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70327. };
  70328. CSG.prototype.subtractInPlace = function (csg) {
  70329. var a = new Node(this.polygons);
  70330. var b = new Node(csg.polygons);
  70331. a.invert();
  70332. a.clipTo(b);
  70333. b.clipTo(a);
  70334. b.invert();
  70335. b.clipTo(a);
  70336. b.invert();
  70337. a.build(b.allPolygons());
  70338. a.invert();
  70339. this.polygons = a.allPolygons();
  70340. };
  70341. CSG.prototype.intersect = function (csg) {
  70342. var a = new Node(this.clone().polygons);
  70343. var b = new Node(csg.clone().polygons);
  70344. a.invert();
  70345. b.clipTo(a);
  70346. b.invert();
  70347. a.clipTo(b);
  70348. b.clipTo(a);
  70349. a.build(b.allPolygons());
  70350. a.invert();
  70351. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  70352. };
  70353. CSG.prototype.intersectInPlace = function (csg) {
  70354. var a = new Node(this.polygons);
  70355. var b = new Node(csg.polygons);
  70356. a.invert();
  70357. b.clipTo(a);
  70358. b.invert();
  70359. a.clipTo(b);
  70360. b.clipTo(a);
  70361. a.build(b.allPolygons());
  70362. a.invert();
  70363. this.polygons = a.allPolygons();
  70364. };
  70365. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  70366. // not modified.
  70367. CSG.prototype.inverse = function () {
  70368. var csg = this.clone();
  70369. csg.inverseInPlace();
  70370. return csg;
  70371. };
  70372. CSG.prototype.inverseInPlace = function () {
  70373. this.polygons.map(function (p) { p.flip(); });
  70374. };
  70375. // This is used to keep meshes transformations so they can be restored
  70376. // when we build back a Babylon Mesh
  70377. // NB : All CSG operations are performed in world coordinates
  70378. CSG.prototype.copyTransformAttributes = function (csg) {
  70379. this.matrix = csg.matrix;
  70380. this.position = csg.position;
  70381. this.rotation = csg.rotation;
  70382. this.scaling = csg.scaling;
  70383. this.rotationQuaternion = csg.rotationQuaternion;
  70384. return this;
  70385. };
  70386. // Build Raw mesh from CSG
  70387. // Coordinates here are in world space
  70388. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  70389. var matrix = this.matrix.clone();
  70390. matrix.invert();
  70391. 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;
  70392. if (keepSubMeshes) {
  70393. // Sort Polygons, since subMeshes are indices range
  70394. polygons.sort(function (a, b) {
  70395. if (a.shared.meshId === b.shared.meshId) {
  70396. return a.shared.subMeshId - b.shared.subMeshId;
  70397. }
  70398. else {
  70399. return a.shared.meshId - b.shared.meshId;
  70400. }
  70401. });
  70402. }
  70403. for (var i = 0, il = polygons.length; i < il; i++) {
  70404. polygon = polygons[i];
  70405. // Building SubMeshes
  70406. if (!subMesh_dict[polygon.shared.meshId]) {
  70407. subMesh_dict[polygon.shared.meshId] = {};
  70408. }
  70409. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  70410. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  70411. indexStart: +Infinity,
  70412. indexEnd: -Infinity,
  70413. materialIndex: polygon.shared.materialIndex
  70414. };
  70415. }
  70416. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  70417. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  70418. polygonIndices[0] = 0;
  70419. polygonIndices[1] = j - 1;
  70420. polygonIndices[2] = j;
  70421. for (var k = 0; k < 3; k++) {
  70422. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  70423. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  70424. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  70425. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  70426. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  70427. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  70428. // Check if 2 points can be merged
  70429. if (!(typeof vertex_idx !== 'undefined' &&
  70430. normals[vertex_idx * 3] === localNormal.x &&
  70431. normals[vertex_idx * 3 + 1] === localNormal.y &&
  70432. normals[vertex_idx * 3 + 2] === localNormal.z &&
  70433. uvs[vertex_idx * 2] === uv.x &&
  70434. uvs[vertex_idx * 2 + 1] === uv.y)) {
  70435. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  70436. uvs.push(uv.x, uv.y);
  70437. normals.push(normal.x, normal.y, normal.z);
  70438. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  70439. }
  70440. indices.push(vertex_idx);
  70441. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  70442. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  70443. currentIndex++;
  70444. }
  70445. }
  70446. }
  70447. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  70448. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  70449. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  70450. mesh.setIndices(indices, null);
  70451. if (keepSubMeshes) {
  70452. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  70453. var materialIndexOffset = 0, materialMaxIndex;
  70454. mesh.subMeshes = new Array();
  70455. for (var m in subMesh_dict) {
  70456. materialMaxIndex = -1;
  70457. for (var sm in subMesh_dict[m]) {
  70458. subMesh_obj = subMesh_dict[m][sm];
  70459. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  70460. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  70461. }
  70462. materialIndexOffset += ++materialMaxIndex;
  70463. }
  70464. }
  70465. return mesh;
  70466. };
  70467. // Build Mesh from CSG taking material and transforms into account
  70468. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  70469. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  70470. mesh.material = material;
  70471. mesh.position.copyFrom(this.position);
  70472. mesh.rotation.copyFrom(this.rotation);
  70473. if (this.rotationQuaternion) {
  70474. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  70475. }
  70476. mesh.scaling.copyFrom(this.scaling);
  70477. mesh.computeWorldMatrix(true);
  70478. return mesh;
  70479. };
  70480. return CSG;
  70481. }());
  70482. BABYLON.CSG = CSG;
  70483. })(BABYLON || (BABYLON = {}));
  70484. //# sourceMappingURL=babylon.csg.js.map
  70485. var BABYLON;
  70486. (function (BABYLON) {
  70487. var LensFlare = /** @class */ (function () {
  70488. function LensFlare(size, position, color, imgUrl, system) {
  70489. this.size = size;
  70490. this.position = position;
  70491. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  70492. this.color = color || new BABYLON.Color3(1, 1, 1);
  70493. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  70494. this._system = system;
  70495. system.lensFlares.push(this);
  70496. }
  70497. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  70498. return new LensFlare(size, position, color, imgUrl, system);
  70499. };
  70500. LensFlare.prototype.dispose = function () {
  70501. if (this.texture) {
  70502. this.texture.dispose();
  70503. }
  70504. // Remove from scene
  70505. var index = this._system.lensFlares.indexOf(this);
  70506. this._system.lensFlares.splice(index, 1);
  70507. };
  70508. ;
  70509. return LensFlare;
  70510. }());
  70511. BABYLON.LensFlare = LensFlare;
  70512. })(BABYLON || (BABYLON = {}));
  70513. //# sourceMappingURL=babylon.lensFlare.js.map
  70514. var BABYLON;
  70515. (function (BABYLON) {
  70516. var LensFlareSystem = /** @class */ (function () {
  70517. function LensFlareSystem(name, emitter, scene) {
  70518. this.name = name;
  70519. this.lensFlares = new Array();
  70520. this.borderLimit = 300;
  70521. this.viewportBorder = 0;
  70522. this.layerMask = 0x0FFFFFFF;
  70523. this._vertexBuffers = {};
  70524. this._isEnabled = true;
  70525. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70526. this._emitter = emitter;
  70527. this.id = name;
  70528. scene.lensFlareSystems.push(this);
  70529. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  70530. var engine = scene.getEngine();
  70531. // VBO
  70532. var vertices = [];
  70533. vertices.push(1, 1);
  70534. vertices.push(-1, 1);
  70535. vertices.push(-1, -1);
  70536. vertices.push(1, -1);
  70537. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70538. // Indices
  70539. var indices = [];
  70540. indices.push(0);
  70541. indices.push(1);
  70542. indices.push(2);
  70543. indices.push(0);
  70544. indices.push(2);
  70545. indices.push(3);
  70546. this._indexBuffer = engine.createIndexBuffer(indices);
  70547. // Effects
  70548. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  70549. }
  70550. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  70551. get: function () {
  70552. return this._isEnabled;
  70553. },
  70554. set: function (value) {
  70555. this._isEnabled = value;
  70556. },
  70557. enumerable: true,
  70558. configurable: true
  70559. });
  70560. LensFlareSystem.prototype.getScene = function () {
  70561. return this._scene;
  70562. };
  70563. LensFlareSystem.prototype.getEmitter = function () {
  70564. return this._emitter;
  70565. };
  70566. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  70567. this._emitter = newEmitter;
  70568. };
  70569. LensFlareSystem.prototype.getEmitterPosition = function () {
  70570. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  70571. };
  70572. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  70573. var position = this.getEmitterPosition();
  70574. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  70575. this._positionX = position.x;
  70576. this._positionY = position.y;
  70577. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  70578. if (this.viewportBorder > 0) {
  70579. globalViewport.x -= this.viewportBorder;
  70580. globalViewport.y -= this.viewportBorder;
  70581. globalViewport.width += this.viewportBorder * 2;
  70582. globalViewport.height += this.viewportBorder * 2;
  70583. position.x += this.viewportBorder;
  70584. position.y += this.viewportBorder;
  70585. this._positionX += this.viewportBorder;
  70586. this._positionY += this.viewportBorder;
  70587. }
  70588. if (position.z > 0) {
  70589. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  70590. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  70591. return true;
  70592. }
  70593. return true;
  70594. }
  70595. return false;
  70596. };
  70597. LensFlareSystem.prototype._isVisible = function () {
  70598. if (!this._isEnabled || !this._scene.activeCamera) {
  70599. return false;
  70600. }
  70601. var emitterPosition = this.getEmitterPosition();
  70602. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  70603. var distance = direction.length();
  70604. direction.normalize();
  70605. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  70606. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  70607. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  70608. };
  70609. LensFlareSystem.prototype.render = function () {
  70610. if (!this._effect.isReady() || !this._scene.activeCamera)
  70611. return false;
  70612. var engine = this._scene.getEngine();
  70613. var viewport = this._scene.activeCamera.viewport;
  70614. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  70615. // Position
  70616. if (!this.computeEffectivePosition(globalViewport)) {
  70617. return false;
  70618. }
  70619. // Visibility
  70620. if (!this._isVisible()) {
  70621. return false;
  70622. }
  70623. // Intensity
  70624. var awayX;
  70625. var awayY;
  70626. if (this._positionX < this.borderLimit + globalViewport.x) {
  70627. awayX = this.borderLimit + globalViewport.x - this._positionX;
  70628. }
  70629. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  70630. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  70631. }
  70632. else {
  70633. awayX = 0;
  70634. }
  70635. if (this._positionY < this.borderLimit + globalViewport.y) {
  70636. awayY = this.borderLimit + globalViewport.y - this._positionY;
  70637. }
  70638. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  70639. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  70640. }
  70641. else {
  70642. awayY = 0;
  70643. }
  70644. var away = (awayX > awayY) ? awayX : awayY;
  70645. away -= this.viewportBorder;
  70646. if (away > this.borderLimit) {
  70647. away = this.borderLimit;
  70648. }
  70649. var intensity = 1.0 - (away / this.borderLimit);
  70650. if (intensity < 0) {
  70651. return false;
  70652. }
  70653. if (intensity > 1.0) {
  70654. intensity = 1.0;
  70655. }
  70656. if (this.viewportBorder > 0) {
  70657. globalViewport.x += this.viewportBorder;
  70658. globalViewport.y += this.viewportBorder;
  70659. globalViewport.width -= this.viewportBorder * 2;
  70660. globalViewport.height -= this.viewportBorder * 2;
  70661. this._positionX -= this.viewportBorder;
  70662. this._positionY -= this.viewportBorder;
  70663. }
  70664. // Position
  70665. var centerX = globalViewport.x + globalViewport.width / 2;
  70666. var centerY = globalViewport.y + globalViewport.height / 2;
  70667. var distX = centerX - this._positionX;
  70668. var distY = centerY - this._positionY;
  70669. // Effects
  70670. engine.enableEffect(this._effect);
  70671. engine.setState(false);
  70672. engine.setDepthBuffer(false);
  70673. // VBOs
  70674. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70675. // Flares
  70676. for (var index = 0; index < this.lensFlares.length; index++) {
  70677. var flare = this.lensFlares[index];
  70678. engine.setAlphaMode(flare.alphaMode);
  70679. var x = centerX - (distX * flare.position);
  70680. var y = centerY - (distY * flare.position);
  70681. var cw = flare.size;
  70682. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  70683. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  70684. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  70685. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  70686. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  70687. // Texture
  70688. this._effect.setTexture("textureSampler", flare.texture);
  70689. // Color
  70690. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  70691. // Draw order
  70692. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70693. }
  70694. engine.setDepthBuffer(true);
  70695. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70696. return true;
  70697. };
  70698. LensFlareSystem.prototype.dispose = function () {
  70699. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70700. if (vertexBuffer) {
  70701. vertexBuffer.dispose();
  70702. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70703. }
  70704. if (this._indexBuffer) {
  70705. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70706. this._indexBuffer = null;
  70707. }
  70708. while (this.lensFlares.length) {
  70709. this.lensFlares[0].dispose();
  70710. }
  70711. // Remove from scene
  70712. var index = this._scene.lensFlareSystems.indexOf(this);
  70713. this._scene.lensFlareSystems.splice(index, 1);
  70714. };
  70715. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  70716. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  70717. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  70718. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  70719. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  70720. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  70721. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  70722. var parsedFlare = parsedLensFlareSystem.flares[index];
  70723. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  70724. }
  70725. return lensFlareSystem;
  70726. };
  70727. LensFlareSystem.prototype.serialize = function () {
  70728. var serializationObject = {};
  70729. serializationObject.id = this.id;
  70730. serializationObject.name = this.name;
  70731. serializationObject.emitterId = this.getEmitter().id;
  70732. serializationObject.borderLimit = this.borderLimit;
  70733. serializationObject.flares = [];
  70734. for (var index = 0; index < this.lensFlares.length; index++) {
  70735. var flare = this.lensFlares[index];
  70736. serializationObject.flares.push({
  70737. size: flare.size,
  70738. position: flare.position,
  70739. color: flare.color.asArray(),
  70740. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  70741. });
  70742. }
  70743. return serializationObject;
  70744. };
  70745. return LensFlareSystem;
  70746. }());
  70747. BABYLON.LensFlareSystem = LensFlareSystem;
  70748. })(BABYLON || (BABYLON = {}));
  70749. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  70750. var BABYLON;
  70751. (function (BABYLON) {
  70752. /**
  70753. * This is a holder class for the physics joint created by the physics plugin.
  70754. * It holds a set of functions to control the underlying joint.
  70755. */
  70756. var PhysicsJoint = /** @class */ (function () {
  70757. function PhysicsJoint(type, jointData) {
  70758. this.type = type;
  70759. this.jointData = jointData;
  70760. jointData.nativeParams = jointData.nativeParams || {};
  70761. }
  70762. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  70763. get: function () {
  70764. return this._physicsJoint;
  70765. },
  70766. set: function (newJoint) {
  70767. if (this._physicsJoint) {
  70768. //remove from the wolrd
  70769. }
  70770. this._physicsJoint = newJoint;
  70771. },
  70772. enumerable: true,
  70773. configurable: true
  70774. });
  70775. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  70776. set: function (physicsPlugin) {
  70777. this._physicsPlugin = physicsPlugin;
  70778. },
  70779. enumerable: true,
  70780. configurable: true
  70781. });
  70782. /**
  70783. * Execute a function that is physics-plugin specific.
  70784. * @param {Function} func the function that will be executed.
  70785. * It accepts two parameters: the physics world and the physics joint.
  70786. */
  70787. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  70788. func(this._physicsPlugin.world, this._physicsJoint);
  70789. };
  70790. //TODO check if the native joints are the same
  70791. //Joint Types
  70792. PhysicsJoint.DistanceJoint = 0;
  70793. PhysicsJoint.HingeJoint = 1;
  70794. PhysicsJoint.BallAndSocketJoint = 2;
  70795. PhysicsJoint.WheelJoint = 3;
  70796. PhysicsJoint.SliderJoint = 4;
  70797. //OIMO
  70798. PhysicsJoint.PrismaticJoint = 5;
  70799. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  70800. PhysicsJoint.UniversalJoint = 6;
  70801. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  70802. //Cannon
  70803. //Similar to a Ball-Joint. Different in params
  70804. PhysicsJoint.PointToPointJoint = 8;
  70805. //Cannon only at the moment
  70806. PhysicsJoint.SpringJoint = 9;
  70807. PhysicsJoint.LockJoint = 10;
  70808. return PhysicsJoint;
  70809. }());
  70810. BABYLON.PhysicsJoint = PhysicsJoint;
  70811. /**
  70812. * A class representing a physics distance joint.
  70813. */
  70814. var DistanceJoint = /** @class */ (function (_super) {
  70815. __extends(DistanceJoint, _super);
  70816. function DistanceJoint(jointData) {
  70817. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  70818. }
  70819. /**
  70820. * Update the predefined distance.
  70821. */
  70822. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  70823. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  70824. };
  70825. return DistanceJoint;
  70826. }(PhysicsJoint));
  70827. BABYLON.DistanceJoint = DistanceJoint;
  70828. var MotorEnabledJoint = /** @class */ (function (_super) {
  70829. __extends(MotorEnabledJoint, _super);
  70830. function MotorEnabledJoint(type, jointData) {
  70831. return _super.call(this, type, jointData) || this;
  70832. }
  70833. /**
  70834. * Set the motor values.
  70835. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70836. * @param {number} force the force to apply
  70837. * @param {number} maxForce max force for this motor.
  70838. */
  70839. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  70840. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70841. };
  70842. /**
  70843. * Set the motor's limits.
  70844. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70845. */
  70846. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70847. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70848. };
  70849. return MotorEnabledJoint;
  70850. }(PhysicsJoint));
  70851. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  70852. /**
  70853. * This class represents a single hinge physics joint
  70854. */
  70855. var HingeJoint = /** @class */ (function (_super) {
  70856. __extends(HingeJoint, _super);
  70857. function HingeJoint(jointData) {
  70858. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  70859. }
  70860. /**
  70861. * Set the motor values.
  70862. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70863. * @param {number} force the force to apply
  70864. * @param {number} maxForce max force for this motor.
  70865. */
  70866. HingeJoint.prototype.setMotor = function (force, maxForce) {
  70867. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70868. };
  70869. /**
  70870. * Set the motor's limits.
  70871. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70872. */
  70873. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70874. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70875. };
  70876. return HingeJoint;
  70877. }(MotorEnabledJoint));
  70878. BABYLON.HingeJoint = HingeJoint;
  70879. /**
  70880. * This class represents a dual hinge physics joint (same as wheel joint)
  70881. */
  70882. var Hinge2Joint = /** @class */ (function (_super) {
  70883. __extends(Hinge2Joint, _super);
  70884. function Hinge2Joint(jointData) {
  70885. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  70886. }
  70887. /**
  70888. * Set the motor values.
  70889. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70890. * @param {number} force the force to apply
  70891. * @param {number} maxForce max force for this motor.
  70892. * @param {motorIndex} the motor's index, 0 or 1.
  70893. */
  70894. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  70895. if (motorIndex === void 0) { motorIndex = 0; }
  70896. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  70897. };
  70898. /**
  70899. * Set the motor limits.
  70900. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70901. * @param {number} upperLimit the upper limit
  70902. * @param {number} lowerLimit lower limit
  70903. * @param {motorIndex} the motor's index, 0 or 1.
  70904. */
  70905. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  70906. if (motorIndex === void 0) { motorIndex = 0; }
  70907. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  70908. };
  70909. return Hinge2Joint;
  70910. }(MotorEnabledJoint));
  70911. BABYLON.Hinge2Joint = Hinge2Joint;
  70912. })(BABYLON || (BABYLON = {}));
  70913. //# sourceMappingURL=babylon.physicsJoint.js.map
  70914. var BABYLON;
  70915. (function (BABYLON) {
  70916. var PhysicsImpostor = /** @class */ (function () {
  70917. function PhysicsImpostor(object, type, _options, _scene) {
  70918. if (_options === void 0) { _options = { mass: 0 }; }
  70919. var _this = this;
  70920. this.object = object;
  70921. this.type = type;
  70922. this._options = _options;
  70923. this._scene = _scene;
  70924. this._bodyUpdateRequired = false;
  70925. this._onBeforePhysicsStepCallbacks = new Array();
  70926. this._onAfterPhysicsStepCallbacks = new Array();
  70927. this._onPhysicsCollideCallbacks = [];
  70928. this._deltaPosition = BABYLON.Vector3.Zero();
  70929. this._isDisposed = false;
  70930. //temp variables for parent rotation calculations
  70931. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  70932. this._tmpQuat = new BABYLON.Quaternion();
  70933. this._tmpQuat2 = new BABYLON.Quaternion();
  70934. /**
  70935. * this function is executed by the physics engine.
  70936. */
  70937. this.beforeStep = function () {
  70938. if (!_this._physicsEngine) {
  70939. return;
  70940. }
  70941. _this.object.translate(_this._deltaPosition, -1);
  70942. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  70943. _this.object.computeWorldMatrix(false);
  70944. if (_this.object.parent && _this.object.rotationQuaternion) {
  70945. _this.getParentsRotation();
  70946. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  70947. }
  70948. else {
  70949. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  70950. }
  70951. if (!_this._options.disableBidirectionalTransformation) {
  70952. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  70953. }
  70954. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  70955. func(_this);
  70956. });
  70957. };
  70958. /**
  70959. * this function is executed by the physics engine.
  70960. */
  70961. this.afterStep = function () {
  70962. if (!_this._physicsEngine) {
  70963. return;
  70964. }
  70965. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  70966. func(_this);
  70967. });
  70968. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  70969. // object has now its world rotation. needs to be converted to local.
  70970. if (_this.object.parent && _this.object.rotationQuaternion) {
  70971. _this.getParentsRotation();
  70972. _this._tmpQuat.conjugateInPlace();
  70973. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  70974. }
  70975. // take the position set and make it the absolute position of this object.
  70976. _this.object.setAbsolutePosition(_this.object.position);
  70977. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  70978. _this.object.translate(_this._deltaPosition, 1);
  70979. };
  70980. /**
  70981. * Legacy collision detection event support
  70982. */
  70983. this.onCollideEvent = null;
  70984. //event and body object due to cannon's event-based architecture.
  70985. this.onCollide = function (e) {
  70986. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  70987. return;
  70988. }
  70989. if (!_this._physicsEngine) {
  70990. return;
  70991. }
  70992. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  70993. if (otherImpostor) {
  70994. // Legacy collision detection event support
  70995. if (_this.onCollideEvent) {
  70996. _this.onCollideEvent(_this, otherImpostor);
  70997. }
  70998. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  70999. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  71000. }).forEach(function (obj) {
  71001. obj.callback(_this, otherImpostor);
  71002. });
  71003. }
  71004. };
  71005. //sanity check!
  71006. if (!this.object) {
  71007. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  71008. return;
  71009. }
  71010. //legacy support for old syntax.
  71011. if (!this._scene && object.getScene) {
  71012. this._scene = object.getScene();
  71013. }
  71014. if (!this._scene) {
  71015. return;
  71016. }
  71017. this._physicsEngine = this._scene.getPhysicsEngine();
  71018. if (!this._physicsEngine) {
  71019. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  71020. }
  71021. else {
  71022. //set the object's quaternion, if not set
  71023. if (!this.object.rotationQuaternion) {
  71024. if (this.object.rotation) {
  71025. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  71026. }
  71027. else {
  71028. this.object.rotationQuaternion = new BABYLON.Quaternion();
  71029. }
  71030. }
  71031. //default options params
  71032. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  71033. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  71034. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  71035. this._joints = [];
  71036. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  71037. if (!this.object.parent || this._options.ignoreParent) {
  71038. this._init();
  71039. }
  71040. else if (this.object.parent.physicsImpostor) {
  71041. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  71042. }
  71043. }
  71044. }
  71045. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  71046. get: function () {
  71047. return this._isDisposed;
  71048. },
  71049. enumerable: true,
  71050. configurable: true
  71051. });
  71052. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  71053. get: function () {
  71054. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  71055. },
  71056. set: function (value) {
  71057. this.setMass(value);
  71058. },
  71059. enumerable: true,
  71060. configurable: true
  71061. });
  71062. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  71063. get: function () {
  71064. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  71065. },
  71066. set: function (value) {
  71067. if (!this._physicsEngine) {
  71068. return;
  71069. }
  71070. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  71071. },
  71072. enumerable: true,
  71073. configurable: true
  71074. });
  71075. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  71076. get: function () {
  71077. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  71078. },
  71079. set: function (value) {
  71080. if (!this._physicsEngine) {
  71081. return;
  71082. }
  71083. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  71084. },
  71085. enumerable: true,
  71086. configurable: true
  71087. });
  71088. /**
  71089. * This function will completly initialize this impostor.
  71090. * It will create a new body - but only if this mesh has no parent.
  71091. * If it has, this impostor will not be used other than to define the impostor
  71092. * of the child mesh.
  71093. */
  71094. PhysicsImpostor.prototype._init = function () {
  71095. if (!this._physicsEngine) {
  71096. return;
  71097. }
  71098. this._physicsEngine.removeImpostor(this);
  71099. this.physicsBody = null;
  71100. this._parent = this._parent || this._getPhysicsParent();
  71101. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  71102. this._physicsEngine.addImpostor(this);
  71103. }
  71104. };
  71105. PhysicsImpostor.prototype._getPhysicsParent = function () {
  71106. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  71107. var parentMesh = this.object.parent;
  71108. return parentMesh.physicsImpostor;
  71109. }
  71110. return null;
  71111. };
  71112. /**
  71113. * Should a new body be generated.
  71114. */
  71115. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  71116. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  71117. };
  71118. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  71119. this.forceUpdate();
  71120. };
  71121. /**
  71122. * Force a regeneration of this or the parent's impostor's body.
  71123. * Use under cautious - This will remove all joints already implemented.
  71124. */
  71125. PhysicsImpostor.prototype.forceUpdate = function () {
  71126. this._init();
  71127. if (this.parent && !this._options.ignoreParent) {
  71128. this.parent.forceUpdate();
  71129. }
  71130. };
  71131. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  71132. /*public get mesh(): AbstractMesh {
  71133. return this._mesh;
  71134. }*/
  71135. /**
  71136. * Gets the body that holds this impostor. Either its own, or its parent.
  71137. */
  71138. get: function () {
  71139. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  71140. },
  71141. /**
  71142. * Set the physics body. Used mainly by the physics engine/plugin
  71143. */
  71144. set: function (physicsBody) {
  71145. if (this._physicsBody && this._physicsEngine) {
  71146. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  71147. }
  71148. this._physicsBody = physicsBody;
  71149. this.resetUpdateFlags();
  71150. },
  71151. enumerable: true,
  71152. configurable: true
  71153. });
  71154. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  71155. get: function () {
  71156. return !this._options.ignoreParent && this._parent ? this._parent : null;
  71157. },
  71158. set: function (value) {
  71159. this._parent = value;
  71160. },
  71161. enumerable: true,
  71162. configurable: true
  71163. });
  71164. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  71165. this._bodyUpdateRequired = false;
  71166. };
  71167. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  71168. if (this.object.getBoundingInfo) {
  71169. var q = this.object.rotationQuaternion;
  71170. //reset rotation
  71171. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  71172. //calculate the world matrix with no rotation
  71173. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71174. var boundingInfo = this.object.getBoundingInfo();
  71175. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  71176. //bring back the rotation
  71177. this.object.rotationQuaternion = q;
  71178. //calculate the world matrix with the new rotation
  71179. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  71180. return size;
  71181. }
  71182. else {
  71183. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  71184. }
  71185. };
  71186. PhysicsImpostor.prototype.getObjectCenter = function () {
  71187. if (this.object.getBoundingInfo) {
  71188. var boundingInfo = this.object.getBoundingInfo();
  71189. return boundingInfo.boundingBox.centerWorld;
  71190. }
  71191. else {
  71192. return this.object.position;
  71193. }
  71194. };
  71195. /**
  71196. * Get a specific parametes from the options parameter.
  71197. */
  71198. PhysicsImpostor.prototype.getParam = function (paramName) {
  71199. return this._options[paramName];
  71200. };
  71201. /**
  71202. * Sets a specific parameter in the options given to the physics plugin
  71203. */
  71204. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  71205. this._options[paramName] = value;
  71206. this._bodyUpdateRequired = true;
  71207. };
  71208. /**
  71209. * Specifically change the body's mass option. Won't recreate the physics body object
  71210. */
  71211. PhysicsImpostor.prototype.setMass = function (mass) {
  71212. if (this.getParam("mass") !== mass) {
  71213. this.setParam("mass", mass);
  71214. }
  71215. if (this._physicsEngine) {
  71216. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  71217. }
  71218. };
  71219. PhysicsImpostor.prototype.getLinearVelocity = function () {
  71220. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  71221. };
  71222. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  71223. if (this._physicsEngine) {
  71224. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  71225. }
  71226. };
  71227. PhysicsImpostor.prototype.getAngularVelocity = function () {
  71228. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  71229. };
  71230. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  71231. if (this._physicsEngine) {
  71232. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  71233. }
  71234. };
  71235. /**
  71236. * Execute a function with the physics plugin native code.
  71237. * Provide a function the will have two variables - the world object and the physics body object.
  71238. */
  71239. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  71240. if (this._physicsEngine) {
  71241. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  71242. }
  71243. };
  71244. /**
  71245. * Register a function that will be executed before the physics world is stepping forward.
  71246. */
  71247. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  71248. this._onBeforePhysicsStepCallbacks.push(func);
  71249. };
  71250. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  71251. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  71252. if (index > -1) {
  71253. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  71254. }
  71255. else {
  71256. BABYLON.Tools.Warn("Function to remove was not found");
  71257. }
  71258. };
  71259. /**
  71260. * Register a function that will be executed after the physics step
  71261. */
  71262. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  71263. this._onAfterPhysicsStepCallbacks.push(func);
  71264. };
  71265. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  71266. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  71267. if (index > -1) {
  71268. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  71269. }
  71270. else {
  71271. BABYLON.Tools.Warn("Function to remove was not found");
  71272. }
  71273. };
  71274. /**
  71275. * register a function that will be executed when this impostor collides against a different body.
  71276. */
  71277. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  71278. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71279. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  71280. };
  71281. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  71282. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  71283. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  71284. if (index > -1) {
  71285. this._onPhysicsCollideCallbacks.splice(index, 1);
  71286. }
  71287. else {
  71288. BABYLON.Tools.Warn("Function to remove was not found");
  71289. }
  71290. };
  71291. PhysicsImpostor.prototype.getParentsRotation = function () {
  71292. var parent = this.object.parent;
  71293. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  71294. while (parent) {
  71295. if (parent.rotationQuaternion) {
  71296. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  71297. }
  71298. else {
  71299. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  71300. }
  71301. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  71302. parent = parent.parent;
  71303. }
  71304. return this._tmpQuat;
  71305. };
  71306. /**
  71307. * Apply a force
  71308. */
  71309. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  71310. if (this._physicsEngine) {
  71311. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  71312. }
  71313. return this;
  71314. };
  71315. /**
  71316. * Apply an impulse
  71317. */
  71318. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  71319. if (this._physicsEngine) {
  71320. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  71321. }
  71322. return this;
  71323. };
  71324. /**
  71325. * A help function to create a joint.
  71326. */
  71327. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  71328. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  71329. this.addJoint(otherImpostor, joint);
  71330. return this;
  71331. };
  71332. /**
  71333. * Add a joint to this impostor with a different impostor.
  71334. */
  71335. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  71336. this._joints.push({
  71337. otherImpostor: otherImpostor,
  71338. joint: joint
  71339. });
  71340. if (this._physicsEngine) {
  71341. this._physicsEngine.addJoint(this, otherImpostor, joint);
  71342. }
  71343. return this;
  71344. };
  71345. /**
  71346. * Will keep this body still, in a sleep mode.
  71347. */
  71348. PhysicsImpostor.prototype.sleep = function () {
  71349. if (this._physicsEngine) {
  71350. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  71351. }
  71352. return this;
  71353. };
  71354. /**
  71355. * Wake the body up.
  71356. */
  71357. PhysicsImpostor.prototype.wakeUp = function () {
  71358. if (this._physicsEngine) {
  71359. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  71360. }
  71361. return this;
  71362. };
  71363. PhysicsImpostor.prototype.clone = function (newObject) {
  71364. if (!newObject)
  71365. return null;
  71366. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  71367. };
  71368. PhysicsImpostor.prototype.dispose = function () {
  71369. var _this = this;
  71370. //no dispose if no physics engine is available.
  71371. if (!this._physicsEngine) {
  71372. return;
  71373. }
  71374. this._joints.forEach(function (j) {
  71375. if (_this._physicsEngine) {
  71376. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  71377. }
  71378. });
  71379. //dispose the physics body
  71380. this._physicsEngine.removeImpostor(this);
  71381. if (this.parent) {
  71382. this.parent.forceUpdate();
  71383. }
  71384. else {
  71385. /*this._object.getChildMeshes().forEach(function(mesh) {
  71386. if (mesh.physicsImpostor) {
  71387. if (disposeChildren) {
  71388. mesh.physicsImpostor.dispose();
  71389. mesh.physicsImpostor = null;
  71390. }
  71391. }
  71392. })*/
  71393. }
  71394. this._isDisposed = true;
  71395. };
  71396. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  71397. this._deltaPosition.copyFrom(position);
  71398. };
  71399. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  71400. if (!this._deltaRotation) {
  71401. this._deltaRotation = new BABYLON.Quaternion();
  71402. }
  71403. this._deltaRotation.copyFrom(rotation);
  71404. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  71405. };
  71406. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  71407. if (this._physicsEngine) {
  71408. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  71409. }
  71410. return this;
  71411. };
  71412. PhysicsImpostor.prototype.getRadius = function () {
  71413. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  71414. };
  71415. /**
  71416. * Sync a bone with this impostor
  71417. * @param bone The bone to sync to the impostor.
  71418. * @param boneMesh The mesh that the bone is influencing.
  71419. * @param jointPivot The pivot of the joint / bone in local space.
  71420. * @param distToJoint Optional distance from the impostor to the joint.
  71421. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71422. */
  71423. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  71424. var tempVec = PhysicsImpostor._tmpVecs[0];
  71425. var mesh = this.object;
  71426. if (mesh.rotationQuaternion) {
  71427. if (adjustRotation) {
  71428. var tempQuat = PhysicsImpostor._tmpQuat;
  71429. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  71430. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  71431. }
  71432. else {
  71433. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  71434. }
  71435. }
  71436. tempVec.x = 0;
  71437. tempVec.y = 0;
  71438. tempVec.z = 0;
  71439. if (jointPivot) {
  71440. tempVec.x = jointPivot.x;
  71441. tempVec.y = jointPivot.y;
  71442. tempVec.z = jointPivot.z;
  71443. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  71444. if (distToJoint === undefined || distToJoint === null) {
  71445. distToJoint = jointPivot.length();
  71446. }
  71447. tempVec.x *= distToJoint;
  71448. tempVec.y *= distToJoint;
  71449. tempVec.z *= distToJoint;
  71450. }
  71451. if (bone.getParent()) {
  71452. tempVec.addInPlace(mesh.getAbsolutePosition());
  71453. bone.setAbsolutePosition(tempVec, boneMesh);
  71454. }
  71455. else {
  71456. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  71457. boneMesh.position.x -= tempVec.x;
  71458. boneMesh.position.y -= tempVec.y;
  71459. boneMesh.position.z -= tempVec.z;
  71460. }
  71461. };
  71462. /**
  71463. * Sync impostor to a bone
  71464. * @param bone The bone that the impostor will be synced to.
  71465. * @param boneMesh The mesh that the bone is influencing.
  71466. * @param jointPivot The pivot of the joint / bone in local space.
  71467. * @param distToJoint Optional distance from the impostor to the joint.
  71468. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  71469. * @param boneAxis Optional vector3 axis the bone is aligned with
  71470. */
  71471. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  71472. var mesh = this.object;
  71473. if (mesh.rotationQuaternion) {
  71474. if (adjustRotation) {
  71475. var tempQuat = PhysicsImpostor._tmpQuat;
  71476. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  71477. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  71478. }
  71479. else {
  71480. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  71481. }
  71482. }
  71483. var pos = PhysicsImpostor._tmpVecs[0];
  71484. var boneDir = PhysicsImpostor._tmpVecs[1];
  71485. if (!boneAxis) {
  71486. boneAxis = PhysicsImpostor._tmpVecs[2];
  71487. boneAxis.x = 0;
  71488. boneAxis.y = 1;
  71489. boneAxis.z = 0;
  71490. }
  71491. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  71492. bone.getAbsolutePositionToRef(boneMesh, pos);
  71493. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  71494. distToJoint = jointPivot.length();
  71495. }
  71496. if (distToJoint !== undefined && distToJoint !== null) {
  71497. pos.x += boneDir.x * distToJoint;
  71498. pos.y += boneDir.y * distToJoint;
  71499. pos.z += boneDir.z * distToJoint;
  71500. }
  71501. mesh.setAbsolutePosition(pos);
  71502. };
  71503. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  71504. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  71505. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71506. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  71507. //Impostor types
  71508. PhysicsImpostor.NoImpostor = 0;
  71509. PhysicsImpostor.SphereImpostor = 1;
  71510. PhysicsImpostor.BoxImpostor = 2;
  71511. PhysicsImpostor.PlaneImpostor = 3;
  71512. PhysicsImpostor.MeshImpostor = 4;
  71513. PhysicsImpostor.CylinderImpostor = 7;
  71514. PhysicsImpostor.ParticleImpostor = 8;
  71515. PhysicsImpostor.HeightmapImpostor = 9;
  71516. return PhysicsImpostor;
  71517. }());
  71518. BABYLON.PhysicsImpostor = PhysicsImpostor;
  71519. })(BABYLON || (BABYLON = {}));
  71520. //# sourceMappingURL=babylon.physicsImpostor.js.map
  71521. var BABYLON;
  71522. (function (BABYLON) {
  71523. var PhysicsEngine = /** @class */ (function () {
  71524. function PhysicsEngine(gravity, _physicsPlugin) {
  71525. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  71526. this._physicsPlugin = _physicsPlugin;
  71527. //new methods and parameters
  71528. this._impostors = [];
  71529. this._joints = [];
  71530. if (!this._physicsPlugin.isSupported()) {
  71531. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  71532. + "Please make sure it is included.");
  71533. }
  71534. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  71535. this.setGravity(gravity);
  71536. this.setTimeStep();
  71537. }
  71538. PhysicsEngine.prototype.setGravity = function (gravity) {
  71539. this.gravity = gravity;
  71540. this._physicsPlugin.setGravity(this.gravity);
  71541. };
  71542. /**
  71543. * Set the time step of the physics engine.
  71544. * default is 1/60.
  71545. * To slow it down, enter 1/600 for example.
  71546. * To speed it up, 1/30
  71547. * @param {number} newTimeStep the new timestep to apply to this world.
  71548. */
  71549. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  71550. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  71551. this._physicsPlugin.setTimeStep(newTimeStep);
  71552. };
  71553. /**
  71554. * Get the time step of the physics engine.
  71555. */
  71556. PhysicsEngine.prototype.getTimeStep = function () {
  71557. return this._physicsPlugin.getTimeStep();
  71558. };
  71559. PhysicsEngine.prototype.dispose = function () {
  71560. this._impostors.forEach(function (impostor) {
  71561. impostor.dispose();
  71562. });
  71563. this._physicsPlugin.dispose();
  71564. };
  71565. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  71566. return this._physicsPlugin.name;
  71567. };
  71568. /**
  71569. * Adding a new impostor for the impostor tracking.
  71570. * This will be done by the impostor itself.
  71571. * @param {PhysicsImpostor} impostor the impostor to add
  71572. */
  71573. PhysicsEngine.prototype.addImpostor = function (impostor) {
  71574. impostor.uniqueId = this._impostors.push(impostor);
  71575. //if no parent, generate the body
  71576. if (!impostor.parent) {
  71577. this._physicsPlugin.generatePhysicsBody(impostor);
  71578. }
  71579. };
  71580. /**
  71581. * Remove an impostor from the engine.
  71582. * This impostor and its mesh will not longer be updated by the physics engine.
  71583. * @param {PhysicsImpostor} impostor the impostor to remove
  71584. */
  71585. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  71586. var index = this._impostors.indexOf(impostor);
  71587. if (index > -1) {
  71588. var removed = this._impostors.splice(index, 1);
  71589. //Is it needed?
  71590. if (removed.length) {
  71591. //this will also remove it from the world.
  71592. removed[0].physicsBody = null;
  71593. }
  71594. }
  71595. };
  71596. /**
  71597. * Add a joint to the physics engine
  71598. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  71599. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  71600. * @param {PhysicsJoint} the joint that will connect both impostors.
  71601. */
  71602. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  71603. var impostorJoint = {
  71604. mainImpostor: mainImpostor,
  71605. connectedImpostor: connectedImpostor,
  71606. joint: joint
  71607. };
  71608. joint.physicsPlugin = this._physicsPlugin;
  71609. this._joints.push(impostorJoint);
  71610. this._physicsPlugin.generateJoint(impostorJoint);
  71611. };
  71612. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  71613. var matchingJoints = this._joints.filter(function (impostorJoint) {
  71614. return (impostorJoint.connectedImpostor === connectedImpostor
  71615. && impostorJoint.joint === joint
  71616. && impostorJoint.mainImpostor === mainImpostor);
  71617. });
  71618. if (matchingJoints.length) {
  71619. this._physicsPlugin.removeJoint(matchingJoints[0]);
  71620. //TODO remove it from the list as well
  71621. }
  71622. };
  71623. /**
  71624. * Called by the scene. no need to call it.
  71625. */
  71626. PhysicsEngine.prototype._step = function (delta) {
  71627. var _this = this;
  71628. //check if any mesh has no body / requires an update
  71629. this._impostors.forEach(function (impostor) {
  71630. if (impostor.isBodyInitRequired()) {
  71631. _this._physicsPlugin.generatePhysicsBody(impostor);
  71632. }
  71633. });
  71634. if (delta > 0.1) {
  71635. delta = 0.1;
  71636. }
  71637. else if (delta <= 0) {
  71638. delta = 1.0 / 60.0;
  71639. }
  71640. this._physicsPlugin.executeStep(delta, this._impostors);
  71641. };
  71642. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  71643. return this._physicsPlugin;
  71644. };
  71645. PhysicsEngine.prototype.getImpostors = function () {
  71646. return this._impostors;
  71647. };
  71648. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  71649. for (var i = 0; i < this._impostors.length; ++i) {
  71650. if (this._impostors[i].object === object) {
  71651. return this._impostors[i];
  71652. }
  71653. }
  71654. return null;
  71655. };
  71656. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  71657. for (var i = 0; i < this._impostors.length; ++i) {
  71658. if (this._impostors[i].physicsBody === body) {
  71659. return this._impostors[i];
  71660. }
  71661. }
  71662. return null;
  71663. };
  71664. // Statics
  71665. PhysicsEngine.Epsilon = 0.001;
  71666. return PhysicsEngine;
  71667. }());
  71668. BABYLON.PhysicsEngine = PhysicsEngine;
  71669. })(BABYLON || (BABYLON = {}));
  71670. //# sourceMappingURL=babylon.physicsEngine.js.map
  71671. var BABYLON;
  71672. (function (BABYLON) {
  71673. var PhysicsHelper = /** @class */ (function () {
  71674. function PhysicsHelper(scene) {
  71675. this._scene = scene;
  71676. this._physicsEngine = this._scene.getPhysicsEngine();
  71677. if (!this._physicsEngine) {
  71678. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  71679. }
  71680. }
  71681. /**
  71682. * @param {Vector3} origin the origin of the explosion
  71683. * @param {number} radius the explosion radius
  71684. * @param {number} strength the explosion strength
  71685. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71686. */
  71687. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  71688. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71689. if (!this._physicsEngine) {
  71690. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  71691. return null;
  71692. }
  71693. var impostors = this._physicsEngine.getImpostors();
  71694. if (impostors.length === 0) {
  71695. return null;
  71696. }
  71697. var event = new PhysicsRadialExplosionEvent(this._scene);
  71698. impostors.forEach(function (impostor) {
  71699. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71700. if (!impostorForceAndContactPoint) {
  71701. return;
  71702. }
  71703. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71704. });
  71705. event.dispose(false);
  71706. return event;
  71707. };
  71708. /**
  71709. * @param {Vector3} origin the origin of the explosion
  71710. * @param {number} radius the explosion radius
  71711. * @param {number} strength the explosion strength
  71712. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71713. */
  71714. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  71715. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71716. if (!this._physicsEngine) {
  71717. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71718. return null;
  71719. }
  71720. var impostors = this._physicsEngine.getImpostors();
  71721. if (impostors.length === 0) {
  71722. return null;
  71723. }
  71724. var event = new PhysicsRadialExplosionEvent(this._scene);
  71725. impostors.forEach(function (impostor) {
  71726. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71727. if (!impostorForceAndContactPoint) {
  71728. return;
  71729. }
  71730. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71731. });
  71732. event.dispose(false);
  71733. return event;
  71734. };
  71735. /**
  71736. * @param {Vector3} origin the origin of the explosion
  71737. * @param {number} radius the explosion radius
  71738. * @param {number} strength the explosion strength
  71739. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71740. */
  71741. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  71742. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71743. if (!this._physicsEngine) {
  71744. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71745. return null;
  71746. }
  71747. var impostors = this._physicsEngine.getImpostors();
  71748. if (impostors.length === 0) {
  71749. return null;
  71750. }
  71751. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  71752. event.dispose(false);
  71753. return event;
  71754. };
  71755. /**
  71756. * @param {Vector3} origin the origin of the updraft
  71757. * @param {number} radius the radius of the updraft
  71758. * @param {number} strength the strength of the updraft
  71759. * @param {number} height the height of the updraft
  71760. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  71761. */
  71762. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  71763. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  71764. if (!this._physicsEngine) {
  71765. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71766. return null;
  71767. }
  71768. if (this._physicsEngine.getImpostors().length === 0) {
  71769. return null;
  71770. }
  71771. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  71772. event.dispose(false);
  71773. return event;
  71774. };
  71775. /**
  71776. * @param {Vector3} origin the of the vortex
  71777. * @param {number} radius the radius of the vortex
  71778. * @param {number} strength the strength of the vortex
  71779. * @param {number} height the height of the vortex
  71780. */
  71781. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  71782. if (!this._physicsEngine) {
  71783. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71784. return null;
  71785. }
  71786. if (this._physicsEngine.getImpostors().length === 0) {
  71787. return null;
  71788. }
  71789. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  71790. event.dispose(false);
  71791. return event;
  71792. };
  71793. return PhysicsHelper;
  71794. }());
  71795. BABYLON.PhysicsHelper = PhysicsHelper;
  71796. /***** Radial explosion *****/
  71797. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  71798. function PhysicsRadialExplosionEvent(scene) {
  71799. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  71800. this._rays = [];
  71801. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  71802. this._scene = scene;
  71803. }
  71804. /**
  71805. * Returns the data related to the radial explosion event (sphere & rays).
  71806. * @returns {PhysicsRadialExplosionEventData}
  71807. */
  71808. PhysicsRadialExplosionEvent.prototype.getData = function () {
  71809. this._dataFetched = true;
  71810. return {
  71811. sphere: this._sphere,
  71812. rays: this._rays,
  71813. };
  71814. };
  71815. /**
  71816. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  71817. * @param impostor
  71818. * @param {Vector3} origin the origin of the explosion
  71819. * @param {number} radius the explosion radius
  71820. * @param {number} strength the explosion strength
  71821. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  71822. * @returns {Nullable<PhysicsForceAndContactPoint>}
  71823. */
  71824. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  71825. if (impostor.mass === 0) {
  71826. return null;
  71827. }
  71828. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  71829. return null;
  71830. }
  71831. if (impostor.object.getClassName() !== 'Mesh') {
  71832. return null;
  71833. }
  71834. var impostorObject = impostor.object;
  71835. var impostorObjectCenter = impostor.getObjectCenter();
  71836. var direction = impostorObjectCenter.subtract(origin);
  71837. var ray = new BABYLON.Ray(origin, direction, radius);
  71838. this._rays.push(ray);
  71839. var hit = ray.intersectsMesh(impostorObject);
  71840. var contactPoint = hit.pickedPoint;
  71841. if (!contactPoint) {
  71842. return null;
  71843. }
  71844. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  71845. if (distanceFromOrigin > radius) {
  71846. return null;
  71847. }
  71848. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  71849. ? strength
  71850. : strength * (1 - (distanceFromOrigin / radius));
  71851. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71852. return { force: force, contactPoint: contactPoint };
  71853. };
  71854. /**
  71855. * Disposes the sphere.
  71856. * @param {bolean} force
  71857. */
  71858. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  71859. var _this = this;
  71860. if (force === void 0) { force = true; }
  71861. if (force) {
  71862. this._sphere.dispose();
  71863. }
  71864. else {
  71865. setTimeout(function () {
  71866. if (!_this._dataFetched) {
  71867. _this._sphere.dispose();
  71868. }
  71869. }, 0);
  71870. }
  71871. };
  71872. /*** Helpers ***/
  71873. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  71874. if (!this._sphere) {
  71875. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  71876. this._sphere.isVisible = false;
  71877. }
  71878. };
  71879. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  71880. var impostorObject = impostor.object;
  71881. this._prepareSphere();
  71882. this._sphere.position = origin;
  71883. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  71884. this._sphere._updateBoundingInfo();
  71885. this._sphere.computeWorldMatrix(true);
  71886. return this._sphere.intersectsMesh(impostorObject, true);
  71887. };
  71888. return PhysicsRadialExplosionEvent;
  71889. }());
  71890. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  71891. /***** Gravitational Field *****/
  71892. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  71893. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  71894. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71895. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71896. this._physicsHelper = physicsHelper;
  71897. this._scene = scene;
  71898. this._origin = origin;
  71899. this._radius = radius;
  71900. this._strength = strength;
  71901. this._falloff = falloff;
  71902. this._tickCallback = this._tick.bind(this);
  71903. }
  71904. /**
  71905. * Returns the data related to the gravitational field event (sphere).
  71906. * @returns {PhysicsGravitationalFieldEventData}
  71907. */
  71908. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  71909. this._dataFetched = true;
  71910. return {
  71911. sphere: this._sphere,
  71912. };
  71913. };
  71914. /**
  71915. * Enables the gravitational field.
  71916. */
  71917. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  71918. this._tickCallback.call(this);
  71919. this._scene.registerBeforeRender(this._tickCallback);
  71920. };
  71921. /**
  71922. * Disables the gravitational field.
  71923. */
  71924. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  71925. this._scene.unregisterBeforeRender(this._tickCallback);
  71926. };
  71927. /**
  71928. * Disposes the sphere.
  71929. * @param {bolean} force
  71930. */
  71931. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  71932. var _this = this;
  71933. if (force === void 0) { force = true; }
  71934. if (force) {
  71935. this._sphere.dispose();
  71936. }
  71937. else {
  71938. setTimeout(function () {
  71939. if (!_this._dataFetched) {
  71940. _this._sphere.dispose();
  71941. }
  71942. }, 0);
  71943. }
  71944. };
  71945. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  71946. // Since the params won't change, we fetch the event only once
  71947. if (this._sphere) {
  71948. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71949. }
  71950. else {
  71951. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71952. if (radialExplosionEvent) {
  71953. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  71954. }
  71955. }
  71956. };
  71957. return PhysicsGravitationalFieldEvent;
  71958. }());
  71959. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  71960. /***** Updraft *****/
  71961. var PhysicsUpdraftEvent = /** @class */ (function () {
  71962. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  71963. this._scene = _scene;
  71964. this._origin = _origin;
  71965. this._radius = _radius;
  71966. this._strength = _strength;
  71967. this._height = _height;
  71968. this._updraftMode = _updraftMode;
  71969. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71970. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  71971. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71972. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71973. this._physicsEngine = this._scene.getPhysicsEngine();
  71974. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71975. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71976. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71977. this._originDirection = this._origin.subtract(this._originTop).normalize();
  71978. }
  71979. this._tickCallback = this._tick.bind(this);
  71980. }
  71981. /**
  71982. * Returns the data related to the updraft event (cylinder).
  71983. * @returns {PhysicsUpdraftEventData}
  71984. */
  71985. PhysicsUpdraftEvent.prototype.getData = function () {
  71986. this._dataFetched = true;
  71987. return {
  71988. cylinder: this._cylinder,
  71989. };
  71990. };
  71991. /**
  71992. * Enables the updraft.
  71993. */
  71994. PhysicsUpdraftEvent.prototype.enable = function () {
  71995. this._tickCallback.call(this);
  71996. this._scene.registerBeforeRender(this._tickCallback);
  71997. };
  71998. /**
  71999. * Disables the cortex.
  72000. */
  72001. PhysicsUpdraftEvent.prototype.disable = function () {
  72002. this._scene.unregisterBeforeRender(this._tickCallback);
  72003. };
  72004. /**
  72005. * Disposes the sphere.
  72006. * @param {bolean} force
  72007. */
  72008. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  72009. var _this = this;
  72010. if (force === void 0) { force = true; }
  72011. if (force) {
  72012. this._cylinder.dispose();
  72013. }
  72014. else {
  72015. setTimeout(function () {
  72016. if (!_this._dataFetched) {
  72017. _this._cylinder.dispose();
  72018. }
  72019. }, 0);
  72020. }
  72021. };
  72022. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72023. if (impostor.mass === 0) {
  72024. return null;
  72025. }
  72026. if (!this._intersectsWithCylinder(impostor)) {
  72027. return null;
  72028. }
  72029. var impostorObjectCenter = impostor.getObjectCenter();
  72030. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  72031. var direction = this._originDirection;
  72032. }
  72033. else {
  72034. var direction = impostorObjectCenter.subtract(this._originTop);
  72035. }
  72036. var multiplier = this._strength * -1;
  72037. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  72038. return { force: force, contactPoint: impostorObjectCenter };
  72039. };
  72040. PhysicsUpdraftEvent.prototype._tick = function () {
  72041. var _this = this;
  72042. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72043. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72044. if (!impostorForceAndContactPoint) {
  72045. return;
  72046. }
  72047. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72048. });
  72049. };
  72050. /*** Helpers ***/
  72051. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  72052. if (!this._cylinder) {
  72053. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  72054. height: this._height,
  72055. diameter: this._radius * 2,
  72056. }, this._scene);
  72057. this._cylinder.isVisible = false;
  72058. }
  72059. };
  72060. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  72061. var impostorObject = impostor.object;
  72062. this._prepareCylinder();
  72063. this._cylinder.position = this._cylinderPosition;
  72064. return this._cylinder.intersectsMesh(impostorObject, true);
  72065. };
  72066. return PhysicsUpdraftEvent;
  72067. }());
  72068. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  72069. /***** Vortex *****/
  72070. var PhysicsVortexEvent = /** @class */ (function () {
  72071. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  72072. this._scene = _scene;
  72073. this._origin = _origin;
  72074. this._radius = _radius;
  72075. this._strength = _strength;
  72076. this._height = _height;
  72077. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  72078. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  72079. this._updraftMultiplier = 0.02;
  72080. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  72081. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  72082. this._physicsEngine = this._scene.getPhysicsEngine();
  72083. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  72084. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  72085. this._tickCallback = this._tick.bind(this);
  72086. }
  72087. /**
  72088. * Returns the data related to the vortex event (cylinder).
  72089. * @returns {PhysicsVortexEventData}
  72090. */
  72091. PhysicsVortexEvent.prototype.getData = function () {
  72092. this._dataFetched = true;
  72093. return {
  72094. cylinder: this._cylinder,
  72095. };
  72096. };
  72097. /**
  72098. * Enables the vortex.
  72099. */
  72100. PhysicsVortexEvent.prototype.enable = function () {
  72101. this._tickCallback.call(this);
  72102. this._scene.registerBeforeRender(this._tickCallback);
  72103. };
  72104. /**
  72105. * Disables the cortex.
  72106. */
  72107. PhysicsVortexEvent.prototype.disable = function () {
  72108. this._scene.unregisterBeforeRender(this._tickCallback);
  72109. };
  72110. /**
  72111. * Disposes the sphere.
  72112. * @param {bolean} force
  72113. */
  72114. PhysicsVortexEvent.prototype.dispose = function (force) {
  72115. var _this = this;
  72116. if (force === void 0) { force = true; }
  72117. if (force) {
  72118. this._cylinder.dispose();
  72119. }
  72120. else {
  72121. setTimeout(function () {
  72122. if (!_this._dataFetched) {
  72123. _this._cylinder.dispose();
  72124. }
  72125. }, 0);
  72126. }
  72127. };
  72128. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  72129. if (impostor.mass === 0) {
  72130. return null;
  72131. }
  72132. if (!this._intersectsWithCylinder(impostor)) {
  72133. return null;
  72134. }
  72135. if (impostor.object.getClassName() !== 'Mesh') {
  72136. return null;
  72137. }
  72138. var impostorObject = impostor.object;
  72139. var impostorObjectCenter = impostor.getObjectCenter();
  72140. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  72141. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  72142. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  72143. var hit = ray.intersectsMesh(impostorObject);
  72144. var contactPoint = hit.pickedPoint;
  72145. if (!contactPoint) {
  72146. return null;
  72147. }
  72148. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  72149. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  72150. var directionToOrigin = contactPoint.normalize();
  72151. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72152. directionToOrigin = directionToOrigin.negate();
  72153. }
  72154. // TODO: find a more physically based solution
  72155. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  72156. var forceX = directionToOrigin.x * this._strength / 8;
  72157. var forceY = directionToOrigin.y * this._updraftMultiplier;
  72158. var forceZ = directionToOrigin.z * this._strength / 8;
  72159. }
  72160. else {
  72161. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  72162. var forceY = this._originTop.y * this._updraftMultiplier;
  72163. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  72164. }
  72165. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  72166. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  72167. return { force: force, contactPoint: impostorObjectCenter };
  72168. };
  72169. PhysicsVortexEvent.prototype._tick = function () {
  72170. var _this = this;
  72171. this._physicsEngine.getImpostors().forEach(function (impostor) {
  72172. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  72173. if (!impostorForceAndContactPoint) {
  72174. return;
  72175. }
  72176. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  72177. });
  72178. };
  72179. /*** Helpers ***/
  72180. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  72181. if (!this._cylinder) {
  72182. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  72183. height: this._height,
  72184. diameter: this._radius * 2,
  72185. }, this._scene);
  72186. this._cylinder.isVisible = false;
  72187. }
  72188. };
  72189. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  72190. var impostorObject = impostor.object;
  72191. this._prepareCylinder();
  72192. this._cylinder.position = this._cylinderPosition;
  72193. return this._cylinder.intersectsMesh(impostorObject, true);
  72194. };
  72195. return PhysicsVortexEvent;
  72196. }());
  72197. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  72198. /***** Enums *****/
  72199. /**
  72200. * The strenght of the force in correspondence to the distance of the affected object
  72201. */
  72202. var PhysicsRadialImpulseFalloff;
  72203. (function (PhysicsRadialImpulseFalloff) {
  72204. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  72205. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  72206. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  72207. /**
  72208. * The strenght of the force in correspondence to the distance of the affected object
  72209. */
  72210. var PhysicsUpdraftMode;
  72211. (function (PhysicsUpdraftMode) {
  72212. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  72213. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  72214. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  72215. })(BABYLON || (BABYLON = {}));
  72216. //# sourceMappingURL=babylon.physicsHelper.js.map
  72217. var BABYLON;
  72218. (function (BABYLON) {
  72219. var CannonJSPlugin = /** @class */ (function () {
  72220. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  72221. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  72222. if (iterations === void 0) { iterations = 10; }
  72223. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  72224. this.name = "CannonJSPlugin";
  72225. this._physicsMaterials = new Array();
  72226. this._fixedTimeStep = 1 / 60;
  72227. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  72228. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  72229. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  72230. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  72231. this._tmpPosition = BABYLON.Vector3.Zero();
  72232. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  72233. this._tmpUnityRotation = new BABYLON.Quaternion();
  72234. if (!this.isSupported()) {
  72235. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  72236. return;
  72237. }
  72238. this._extendNamespace();
  72239. this.world = new this.BJSCANNON.World();
  72240. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  72241. this.world.solver.iterations = iterations;
  72242. }
  72243. CannonJSPlugin.prototype.setGravity = function (gravity) {
  72244. this.world.gravity.copy(gravity);
  72245. };
  72246. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  72247. this._fixedTimeStep = timeStep;
  72248. };
  72249. CannonJSPlugin.prototype.getTimeStep = function () {
  72250. return this._fixedTimeStep;
  72251. };
  72252. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  72253. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  72254. };
  72255. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72256. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72257. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72258. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  72259. };
  72260. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72261. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  72262. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  72263. impostor.physicsBody.applyForce(impulse, worldPoint);
  72264. };
  72265. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72266. //parent-child relationship. Does this impostor has a parent impostor?
  72267. if (impostor.parent) {
  72268. if (impostor.physicsBody) {
  72269. this.removePhysicsBody(impostor);
  72270. //TODO is that needed?
  72271. impostor.forceUpdate();
  72272. }
  72273. return;
  72274. }
  72275. //should a new body be created for this impostor?
  72276. if (impostor.isBodyInitRequired()) {
  72277. var shape = this._createShape(impostor);
  72278. //unregister events, if body is being changed
  72279. var oldBody = impostor.physicsBody;
  72280. if (oldBody) {
  72281. this.removePhysicsBody(impostor);
  72282. }
  72283. //create the body and material
  72284. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  72285. var bodyCreationObject = {
  72286. mass: impostor.getParam("mass"),
  72287. material: material
  72288. };
  72289. // A simple extend, in case native options were used.
  72290. var nativeOptions = impostor.getParam("nativeOptions");
  72291. for (var key in nativeOptions) {
  72292. if (nativeOptions.hasOwnProperty(key)) {
  72293. bodyCreationObject[key] = nativeOptions[key];
  72294. }
  72295. }
  72296. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  72297. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  72298. this.world.addEventListener("preStep", impostor.beforeStep);
  72299. this.world.addEventListener("postStep", impostor.afterStep);
  72300. impostor.physicsBody.addShape(shape);
  72301. this.world.add(impostor.physicsBody);
  72302. //try to keep the body moving in the right direction by taking old properties.
  72303. //Should be tested!
  72304. if (oldBody) {
  72305. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  72306. impostor.physicsBody[param].copy(oldBody[param]);
  72307. });
  72308. }
  72309. this._processChildMeshes(impostor);
  72310. }
  72311. //now update the body's transformation
  72312. this._updatePhysicsBodyTransformation(impostor);
  72313. };
  72314. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  72315. var _this = this;
  72316. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  72317. var currentRotation = mainImpostor.object.rotationQuaternion;
  72318. if (meshChildren.length) {
  72319. var processMesh = function (localPosition, mesh) {
  72320. if (!currentRotation || !mesh.rotationQuaternion) {
  72321. return;
  72322. }
  72323. var childImpostor = mesh.getPhysicsImpostor();
  72324. if (childImpostor) {
  72325. var parent = childImpostor.parent;
  72326. if (parent !== mainImpostor) {
  72327. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  72328. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  72329. if (childImpostor.physicsBody) {
  72330. _this.removePhysicsBody(childImpostor);
  72331. childImpostor.physicsBody = null;
  72332. }
  72333. childImpostor.parent = mainImpostor;
  72334. childImpostor.resetUpdateFlags();
  72335. 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));
  72336. //Add the mass of the children.
  72337. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  72338. }
  72339. }
  72340. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  72341. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  72342. };
  72343. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  72344. }
  72345. };
  72346. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72347. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  72348. this.world.removeEventListener("preStep", impostor.beforeStep);
  72349. this.world.removeEventListener("postStep", impostor.afterStep);
  72350. this.world.remove(impostor.physicsBody);
  72351. };
  72352. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72353. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72354. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72355. if (!mainBody || !connectedBody) {
  72356. return;
  72357. }
  72358. var constraint;
  72359. var jointData = impostorJoint.joint.jointData;
  72360. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  72361. var constraintData = {
  72362. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  72363. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  72364. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  72365. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  72366. maxForce: jointData.nativeParams.maxForce,
  72367. collideConnected: !!jointData.collision
  72368. };
  72369. switch (impostorJoint.joint.type) {
  72370. case BABYLON.PhysicsJoint.HingeJoint:
  72371. case BABYLON.PhysicsJoint.Hinge2Joint:
  72372. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  72373. break;
  72374. case BABYLON.PhysicsJoint.DistanceJoint:
  72375. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  72376. break;
  72377. case BABYLON.PhysicsJoint.SpringJoint:
  72378. var springData = jointData;
  72379. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  72380. restLength: springData.length,
  72381. stiffness: springData.stiffness,
  72382. damping: springData.damping,
  72383. localAnchorA: constraintData.pivotA,
  72384. localAnchorB: constraintData.pivotB
  72385. });
  72386. break;
  72387. case BABYLON.PhysicsJoint.LockJoint:
  72388. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  72389. break;
  72390. case BABYLON.PhysicsJoint.PointToPointJoint:
  72391. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72392. default:
  72393. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  72394. break;
  72395. }
  72396. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  72397. constraint.collideConnected = !!jointData.collision;
  72398. impostorJoint.joint.physicsJoint = constraint;
  72399. //don't add spring as constraint, as it is not one.
  72400. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  72401. this.world.addConstraint(constraint);
  72402. }
  72403. else {
  72404. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  72405. constraint.applyForce();
  72406. });
  72407. }
  72408. };
  72409. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72410. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  72411. };
  72412. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  72413. var index;
  72414. var mat;
  72415. for (index = 0; index < this._physicsMaterials.length; index++) {
  72416. mat = this._physicsMaterials[index];
  72417. if (mat.friction === friction && mat.restitution === restitution) {
  72418. return mat;
  72419. }
  72420. }
  72421. var currentMat = new this.BJSCANNON.Material(name);
  72422. currentMat.friction = friction;
  72423. currentMat.restitution = restitution;
  72424. this._physicsMaterials.push(currentMat);
  72425. return currentMat;
  72426. };
  72427. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  72428. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  72429. };
  72430. CannonJSPlugin.prototype._createShape = function (impostor) {
  72431. var object = impostor.object;
  72432. var returnValue;
  72433. var extendSize = impostor.getObjectExtendSize();
  72434. switch (impostor.type) {
  72435. case BABYLON.PhysicsImpostor.SphereImpostor:
  72436. var radiusX = extendSize.x;
  72437. var radiusY = extendSize.y;
  72438. var radiusZ = extendSize.z;
  72439. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  72440. break;
  72441. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  72442. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72443. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  72444. break;
  72445. case BABYLON.PhysicsImpostor.BoxImpostor:
  72446. var box = extendSize.scale(0.5);
  72447. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  72448. break;
  72449. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72450. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  72451. returnValue = new this.BJSCANNON.Plane();
  72452. break;
  72453. case BABYLON.PhysicsImpostor.MeshImpostor:
  72454. // should transform the vertex data to world coordinates!!
  72455. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  72456. var rawFaces = object.getIndices ? object.getIndices() : [];
  72457. if (!rawVerts)
  72458. return;
  72459. // get only scale! so the object could transform correctly.
  72460. var oldPosition = object.position.clone();
  72461. var oldRotation = object.rotation && object.rotation.clone();
  72462. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  72463. object.position.copyFromFloats(0, 0, 0);
  72464. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72465. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72466. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72467. var transform = object.computeWorldMatrix(true);
  72468. // convert rawVerts to object space
  72469. var temp = new Array();
  72470. var index;
  72471. for (index = 0; index < rawVerts.length; index += 3) {
  72472. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  72473. }
  72474. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  72475. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  72476. //now set back the transformation!
  72477. object.position.copyFrom(oldPosition);
  72478. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  72479. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  72480. break;
  72481. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  72482. var oldPosition2 = object.position.clone();
  72483. var oldRotation2 = object.rotation && object.rotation.clone();
  72484. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  72485. object.position.copyFromFloats(0, 0, 0);
  72486. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  72487. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  72488. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  72489. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  72490. returnValue = this._createHeightmap(object);
  72491. object.position.copyFrom(oldPosition2);
  72492. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  72493. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  72494. object.computeWorldMatrix(true);
  72495. break;
  72496. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72497. returnValue = new this.BJSCANNON.Particle();
  72498. break;
  72499. }
  72500. return returnValue;
  72501. };
  72502. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  72503. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  72504. var transform = object.computeWorldMatrix(true);
  72505. // convert rawVerts to object space
  72506. var temp = new Array();
  72507. var index;
  72508. for (index = 0; index < pos.length; index += 3) {
  72509. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  72510. }
  72511. pos = temp;
  72512. var matrix = new Array();
  72513. //For now pointDepth will not be used and will be automatically calculated.
  72514. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  72515. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  72516. var boundingInfo = object.getBoundingInfo();
  72517. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  72518. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  72519. var elementSize = dim * 2 / arraySize;
  72520. for (var i = 0; i < pos.length; i = i + 3) {
  72521. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  72522. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  72523. var y = -pos[i + 2] + minY;
  72524. if (!matrix[x]) {
  72525. matrix[x] = [];
  72526. }
  72527. if (!matrix[x][z]) {
  72528. matrix[x][z] = y;
  72529. }
  72530. matrix[x][z] = Math.max(y, matrix[x][z]);
  72531. }
  72532. for (var x = 0; x <= arraySize; ++x) {
  72533. if (!matrix[x]) {
  72534. var loc = 1;
  72535. while (!matrix[(x + loc) % arraySize]) {
  72536. loc++;
  72537. }
  72538. matrix[x] = matrix[(x + loc) % arraySize].slice();
  72539. //console.log("missing x", x);
  72540. }
  72541. for (var z = 0; z <= arraySize; ++z) {
  72542. if (!matrix[x][z]) {
  72543. var loc = 1;
  72544. var newValue;
  72545. while (newValue === undefined) {
  72546. newValue = matrix[x][(z + loc++) % arraySize];
  72547. }
  72548. matrix[x][z] = newValue;
  72549. }
  72550. }
  72551. }
  72552. var shape = new this.BJSCANNON.Heightfield(matrix, {
  72553. elementSize: elementSize
  72554. });
  72555. //For future reference, needed for body transformation
  72556. shape.minY = minY;
  72557. return shape;
  72558. };
  72559. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  72560. var object = impostor.object;
  72561. //make sure it is updated...
  72562. object.computeWorldMatrix && object.computeWorldMatrix(true);
  72563. // The delta between the mesh position and the mesh bounding box center
  72564. var bInfo = object.getBoundingInfo();
  72565. if (!bInfo)
  72566. return;
  72567. var center = impostor.getObjectCenter();
  72568. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  72569. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  72570. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  72571. this._tmpPosition.copyFrom(center);
  72572. var quaternion = object.rotationQuaternion;
  72573. if (!quaternion) {
  72574. return;
  72575. }
  72576. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  72577. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  72578. //-90 DEG in X, precalculated
  72579. quaternion = quaternion.multiply(this._minus90X);
  72580. //Invert! (Precalculated, 90 deg in X)
  72581. //No need to clone. this will never change.
  72582. impostor.setDeltaRotation(this._plus90X);
  72583. }
  72584. //If it is a heightfield, if should be centered.
  72585. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  72586. var mesh = object;
  72587. var boundingInfo = mesh.getBoundingInfo();
  72588. //calculate the correct body position:
  72589. var rotationQuaternion = mesh.rotationQuaternion;
  72590. mesh.rotationQuaternion = this._tmpUnityRotation;
  72591. mesh.computeWorldMatrix(true);
  72592. //get original center with no rotation
  72593. var c = center.clone();
  72594. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  72595. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  72596. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  72597. mesh.setPivotMatrix(p);
  72598. mesh.computeWorldMatrix(true);
  72599. //calculate the translation
  72600. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  72601. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  72602. //add it inverted to the delta
  72603. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  72604. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  72605. //rotation is back
  72606. mesh.rotationQuaternion = rotationQuaternion;
  72607. mesh.setPivotMatrix(oldPivot);
  72608. mesh.computeWorldMatrix(true);
  72609. }
  72610. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  72611. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  72612. //this._tmpPosition.copyFrom(object.position);
  72613. }
  72614. impostor.setDeltaPosition(this._tmpDeltaPosition);
  72615. //Now update the impostor object
  72616. impostor.physicsBody.position.copy(this._tmpPosition);
  72617. impostor.physicsBody.quaternion.copy(quaternion);
  72618. };
  72619. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  72620. impostor.object.position.copyFrom(impostor.physicsBody.position);
  72621. if (impostor.object.rotationQuaternion) {
  72622. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  72623. }
  72624. };
  72625. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  72626. impostor.physicsBody.position.copy(newPosition);
  72627. impostor.physicsBody.quaternion.copy(newRotation);
  72628. };
  72629. CannonJSPlugin.prototype.isSupported = function () {
  72630. return this.BJSCANNON !== undefined;
  72631. };
  72632. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  72633. impostor.physicsBody.velocity.copy(velocity);
  72634. };
  72635. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  72636. impostor.physicsBody.angularVelocity.copy(velocity);
  72637. };
  72638. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  72639. var v = impostor.physicsBody.velocity;
  72640. if (!v) {
  72641. return null;
  72642. }
  72643. return new BABYLON.Vector3(v.x, v.y, v.z);
  72644. };
  72645. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  72646. var v = impostor.physicsBody.angularVelocity;
  72647. if (!v) {
  72648. return null;
  72649. }
  72650. return new BABYLON.Vector3(v.x, v.y, v.z);
  72651. };
  72652. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  72653. impostor.physicsBody.mass = mass;
  72654. impostor.physicsBody.updateMassProperties();
  72655. };
  72656. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  72657. return impostor.physicsBody.mass;
  72658. };
  72659. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  72660. return impostor.physicsBody.material.friction;
  72661. };
  72662. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  72663. impostor.physicsBody.material.friction = friction;
  72664. };
  72665. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  72666. return impostor.physicsBody.material.restitution;
  72667. };
  72668. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  72669. impostor.physicsBody.material.restitution = restitution;
  72670. };
  72671. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  72672. impostor.physicsBody.sleep();
  72673. };
  72674. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  72675. impostor.physicsBody.wakeUp();
  72676. };
  72677. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  72678. joint.physicsJoint.distance = maxDistance;
  72679. };
  72680. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72681. // if (!motorIndex) {
  72682. // joint.physicsJoint.enableMotor();
  72683. // }
  72684. // }
  72685. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72686. // if (!motorIndex) {
  72687. // joint.physicsJoint.disableMotor();
  72688. // }
  72689. // }
  72690. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  72691. if (!motorIndex) {
  72692. joint.physicsJoint.enableMotor();
  72693. joint.physicsJoint.setMotorSpeed(speed);
  72694. if (maxForce) {
  72695. this.setLimit(joint, maxForce);
  72696. }
  72697. }
  72698. };
  72699. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  72700. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  72701. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  72702. };
  72703. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  72704. var body = impostor.physicsBody;
  72705. mesh.position.x = body.position.x;
  72706. mesh.position.y = body.position.y;
  72707. mesh.position.z = body.position.z;
  72708. if (mesh.rotationQuaternion) {
  72709. mesh.rotationQuaternion.x = body.quaternion.x;
  72710. mesh.rotationQuaternion.y = body.quaternion.y;
  72711. mesh.rotationQuaternion.z = body.quaternion.z;
  72712. mesh.rotationQuaternion.w = body.quaternion.w;
  72713. }
  72714. };
  72715. CannonJSPlugin.prototype.getRadius = function (impostor) {
  72716. var shape = impostor.physicsBody.shapes[0];
  72717. return shape.boundingSphereRadius;
  72718. };
  72719. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  72720. var shape = impostor.physicsBody.shapes[0];
  72721. result.x = shape.halfExtents.x * 2;
  72722. result.y = shape.halfExtents.y * 2;
  72723. result.z = shape.halfExtents.z * 2;
  72724. };
  72725. CannonJSPlugin.prototype.dispose = function () {
  72726. };
  72727. CannonJSPlugin.prototype._extendNamespace = function () {
  72728. //this will force cannon to execute at least one step when using interpolation
  72729. var step_tmp1 = new this.BJSCANNON.Vec3();
  72730. var Engine = this.BJSCANNON;
  72731. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  72732. maxSubSteps = maxSubSteps || 10;
  72733. timeSinceLastCalled = timeSinceLastCalled || 0;
  72734. if (timeSinceLastCalled === 0) {
  72735. this.internalStep(dt);
  72736. this.time += dt;
  72737. }
  72738. else {
  72739. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  72740. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  72741. var t0 = performance.now();
  72742. for (var i = 0; i !== internalSteps; i++) {
  72743. this.internalStep(dt);
  72744. if (performance.now() - t0 > dt * 1000) {
  72745. break;
  72746. }
  72747. }
  72748. this.time += timeSinceLastCalled;
  72749. var h = this.time % dt;
  72750. var h_div_dt = h / dt;
  72751. var interpvelo = step_tmp1;
  72752. var bodies = this.bodies;
  72753. for (var j = 0; j !== bodies.length; j++) {
  72754. var b = bodies[j];
  72755. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  72756. b.position.vsub(b.previousPosition, interpvelo);
  72757. interpvelo.scale(h_div_dt, interpvelo);
  72758. b.position.vadd(interpvelo, b.interpolatedPosition);
  72759. }
  72760. else {
  72761. b.interpolatedPosition.copy(b.position);
  72762. b.interpolatedQuaternion.copy(b.quaternion);
  72763. }
  72764. }
  72765. }
  72766. };
  72767. };
  72768. return CannonJSPlugin;
  72769. }());
  72770. BABYLON.CannonJSPlugin = CannonJSPlugin;
  72771. })(BABYLON || (BABYLON = {}));
  72772. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  72773. var BABYLON;
  72774. (function (BABYLON) {
  72775. var OimoJSPlugin = /** @class */ (function () {
  72776. function OimoJSPlugin(iterations) {
  72777. this.name = "OimoJSPlugin";
  72778. this._tmpImpostorsArray = [];
  72779. this._tmpPositionVector = BABYLON.Vector3.Zero();
  72780. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  72781. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  72782. this.world.worldscale(1);
  72783. this.world.clear();
  72784. //making sure no stats are calculated
  72785. this.world.isNoStat = true;
  72786. }
  72787. OimoJSPlugin.prototype.setGravity = function (gravity) {
  72788. this.world.gravity.copy(gravity);
  72789. };
  72790. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  72791. this.world.timeStep = timeStep;
  72792. };
  72793. OimoJSPlugin.prototype.getTimeStep = function () {
  72794. return this.world.timeStep;
  72795. };
  72796. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  72797. var _this = this;
  72798. impostors.forEach(function (impostor) {
  72799. impostor.beforeStep();
  72800. });
  72801. this.world.step();
  72802. impostors.forEach(function (impostor) {
  72803. impostor.afterStep();
  72804. //update the ordered impostors array
  72805. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  72806. });
  72807. //check for collisions
  72808. var contact = this.world.contacts;
  72809. while (contact !== null) {
  72810. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  72811. contact = contact.next;
  72812. continue;
  72813. }
  72814. //is this body colliding with any other? get the impostor
  72815. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  72816. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  72817. if (!mainImpostor || !collidingImpostor) {
  72818. contact = contact.next;
  72819. continue;
  72820. }
  72821. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  72822. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  72823. contact = contact.next;
  72824. }
  72825. };
  72826. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72827. var mass = impostor.physicsBody.massInfo.mass;
  72828. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  72829. };
  72830. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72831. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  72832. this.applyImpulse(impostor, force, contactPoint);
  72833. };
  72834. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72835. var _this = this;
  72836. //parent-child relationship. Does this impostor has a parent impostor?
  72837. if (impostor.parent) {
  72838. if (impostor.physicsBody) {
  72839. this.removePhysicsBody(impostor);
  72840. //TODO is that needed?
  72841. impostor.forceUpdate();
  72842. }
  72843. return;
  72844. }
  72845. if (impostor.isBodyInitRequired()) {
  72846. var bodyConfig = {
  72847. name: impostor.uniqueId,
  72848. //Oimo must have mass, also for static objects.
  72849. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  72850. size: [],
  72851. type: [],
  72852. pos: [],
  72853. rot: [],
  72854. move: impostor.getParam("mass") !== 0,
  72855. //Supporting older versions of Oimo
  72856. world: this.world
  72857. };
  72858. var impostors = [impostor];
  72859. var addToArray = function (parent) {
  72860. if (!parent.getChildMeshes)
  72861. return;
  72862. parent.getChildMeshes().forEach(function (m) {
  72863. if (m.physicsImpostor) {
  72864. impostors.push(m.physicsImpostor);
  72865. //m.physicsImpostor._init();
  72866. }
  72867. });
  72868. };
  72869. addToArray(impostor.object);
  72870. var checkWithEpsilon_1 = function (value) {
  72871. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  72872. };
  72873. impostors.forEach(function (i) {
  72874. if (!impostor.object.rotationQuaternion) {
  72875. return;
  72876. }
  72877. //get the correct bounding box
  72878. var oldQuaternion = i.object.rotationQuaternion;
  72879. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  72880. x: impostor.object.rotationQuaternion.x,
  72881. y: impostor.object.rotationQuaternion.y,
  72882. z: impostor.object.rotationQuaternion.z,
  72883. s: impostor.object.rotationQuaternion.w
  72884. });
  72885. var extendSize = i.getObjectExtendSize();
  72886. if (i === impostor) {
  72887. var center = impostor.getObjectCenter();
  72888. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  72889. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  72890. //Can also use Array.prototype.push.apply
  72891. bodyConfig.pos.push(center.x);
  72892. bodyConfig.pos.push(center.y);
  72893. bodyConfig.pos.push(center.z);
  72894. //tmp solution
  72895. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72896. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72897. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72898. }
  72899. else {
  72900. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  72901. bodyConfig.pos.push(localPosition.x);
  72902. bodyConfig.pos.push(localPosition.y);
  72903. bodyConfig.pos.push(localPosition.z);
  72904. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  72905. bodyConfig.rot.push(0);
  72906. bodyConfig.rot.push(0);
  72907. bodyConfig.rot.push(0);
  72908. }
  72909. // register mesh
  72910. switch (i.type) {
  72911. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72912. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  72913. case BABYLON.PhysicsImpostor.SphereImpostor:
  72914. var radiusX = extendSize.x;
  72915. var radiusY = extendSize.y;
  72916. var radiusZ = extendSize.z;
  72917. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  72918. bodyConfig.type.push('sphere');
  72919. //due to the way oimo works with compounds, add 3 times
  72920. bodyConfig.size.push(size);
  72921. bodyConfig.size.push(size);
  72922. bodyConfig.size.push(size);
  72923. break;
  72924. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72925. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  72926. var sizeY = checkWithEpsilon_1(extendSize.y);
  72927. bodyConfig.type.push('cylinder');
  72928. bodyConfig.size.push(sizeX);
  72929. bodyConfig.size.push(sizeY);
  72930. //due to the way oimo works with compounds, add one more value.
  72931. bodyConfig.size.push(sizeY);
  72932. break;
  72933. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72934. case BABYLON.PhysicsImpostor.BoxImpostor:
  72935. default:
  72936. var sizeX = checkWithEpsilon_1(extendSize.x);
  72937. var sizeY = checkWithEpsilon_1(extendSize.y);
  72938. var sizeZ = checkWithEpsilon_1(extendSize.z);
  72939. bodyConfig.type.push('box');
  72940. bodyConfig.size.push(sizeX);
  72941. bodyConfig.size.push(sizeY);
  72942. bodyConfig.size.push(sizeZ);
  72943. break;
  72944. }
  72945. //actually not needed, but hey...
  72946. i.object.rotationQuaternion = oldQuaternion;
  72947. });
  72948. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  72949. }
  72950. else {
  72951. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  72952. }
  72953. impostor.setDeltaPosition(this._tmpPositionVector);
  72954. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  72955. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  72956. };
  72957. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72958. //impostor.physicsBody.dispose();
  72959. //Same as : (older oimo versions)
  72960. this.world.removeRigidBody(impostor.physicsBody);
  72961. };
  72962. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72963. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72964. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72965. if (!mainBody || !connectedBody) {
  72966. return;
  72967. }
  72968. var jointData = impostorJoint.joint.jointData;
  72969. var options = jointData.nativeParams || {};
  72970. var type;
  72971. var nativeJointData = {
  72972. body1: mainBody,
  72973. body2: connectedBody,
  72974. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  72975. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  72976. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  72977. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  72978. min: options.min,
  72979. max: options.max,
  72980. collision: options.collision || jointData.collision,
  72981. spring: options.spring,
  72982. //supporting older version of Oimo
  72983. world: this.world
  72984. };
  72985. switch (impostorJoint.joint.type) {
  72986. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72987. type = "jointBall";
  72988. break;
  72989. case BABYLON.PhysicsJoint.SpringJoint:
  72990. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  72991. var springData = jointData;
  72992. nativeJointData.min = springData.length || nativeJointData.min;
  72993. //Max should also be set, just make sure it is at least min
  72994. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  72995. case BABYLON.PhysicsJoint.DistanceJoint:
  72996. type = "jointDistance";
  72997. nativeJointData.max = jointData.maxDistance;
  72998. break;
  72999. case BABYLON.PhysicsJoint.PrismaticJoint:
  73000. type = "jointPrisme";
  73001. break;
  73002. case BABYLON.PhysicsJoint.SliderJoint:
  73003. type = "jointSlide";
  73004. break;
  73005. case BABYLON.PhysicsJoint.WheelJoint:
  73006. type = "jointWheel";
  73007. break;
  73008. case BABYLON.PhysicsJoint.HingeJoint:
  73009. default:
  73010. type = "jointHinge";
  73011. break;
  73012. }
  73013. nativeJointData.type = type;
  73014. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  73015. };
  73016. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  73017. //Bug in Oimo prevents us from disposing a joint in the playground
  73018. //joint.joint.physicsJoint.dispose();
  73019. //So we will bruteforce it!
  73020. try {
  73021. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  73022. }
  73023. catch (e) {
  73024. BABYLON.Tools.Warn(e);
  73025. }
  73026. };
  73027. OimoJSPlugin.prototype.isSupported = function () {
  73028. return this.BJSOIMO !== undefined;
  73029. };
  73030. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  73031. if (!impostor.physicsBody.sleeping) {
  73032. //TODO check that
  73033. if (impostor.physicsBody.shapes.next) {
  73034. var parentShape = this._getLastShape(impostor.physicsBody);
  73035. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  73036. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  73037. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  73038. }
  73039. else {
  73040. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  73041. }
  73042. if (impostor.object.rotationQuaternion) {
  73043. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  73044. impostor.object.rotationQuaternion.normalize();
  73045. }
  73046. }
  73047. };
  73048. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  73049. var body = impostor.physicsBody;
  73050. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  73051. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  73052. body.syncShapes();
  73053. body.awake();
  73054. };
  73055. OimoJSPlugin.prototype._getLastShape = function (body) {
  73056. var lastShape = body.shapes;
  73057. while (lastShape.next) {
  73058. lastShape = lastShape.next;
  73059. }
  73060. return lastShape;
  73061. };
  73062. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  73063. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  73064. };
  73065. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  73066. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  73067. };
  73068. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  73069. var v = impostor.physicsBody.linearVelocity;
  73070. if (!v) {
  73071. return null;
  73072. }
  73073. return new BABYLON.Vector3(v.x, v.y, v.z);
  73074. };
  73075. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  73076. var v = impostor.physicsBody.angularVelocity;
  73077. if (!v) {
  73078. return null;
  73079. }
  73080. return new BABYLON.Vector3(v.x, v.y, v.z);
  73081. };
  73082. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  73083. var staticBody = mass === 0;
  73084. //this will actually set the body's density and not its mass.
  73085. //But this is how oimo treats the mass variable.
  73086. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  73087. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  73088. };
  73089. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  73090. return impostor.physicsBody.shapes.density;
  73091. };
  73092. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  73093. return impostor.physicsBody.shapes.friction;
  73094. };
  73095. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  73096. impostor.physicsBody.shapes.friction = friction;
  73097. };
  73098. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  73099. return impostor.physicsBody.shapes.restitution;
  73100. };
  73101. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  73102. impostor.physicsBody.shapes.restitution = restitution;
  73103. };
  73104. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  73105. impostor.physicsBody.sleep();
  73106. };
  73107. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  73108. impostor.physicsBody.awake();
  73109. };
  73110. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  73111. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  73112. if (minDistance !== void 0) {
  73113. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  73114. }
  73115. };
  73116. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  73117. //TODO separate rotational and transational motors.
  73118. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73119. if (motor) {
  73120. motor.setMotor(speed, maxForce);
  73121. }
  73122. };
  73123. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  73124. //TODO separate rotational and transational motors.
  73125. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  73126. if (motor) {
  73127. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  73128. }
  73129. };
  73130. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  73131. var body = impostor.physicsBody;
  73132. mesh.position.x = body.position.x;
  73133. mesh.position.y = body.position.y;
  73134. mesh.position.z = body.position.z;
  73135. if (mesh.rotationQuaternion) {
  73136. mesh.rotationQuaternion.x = body.orientation.x;
  73137. mesh.rotationQuaternion.y = body.orientation.y;
  73138. mesh.rotationQuaternion.z = body.orientation.z;
  73139. mesh.rotationQuaternion.w = body.orientation.s;
  73140. }
  73141. };
  73142. OimoJSPlugin.prototype.getRadius = function (impostor) {
  73143. return impostor.physicsBody.shapes.radius;
  73144. };
  73145. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  73146. var shape = impostor.physicsBody.shapes;
  73147. result.x = shape.halfWidth * 2;
  73148. result.y = shape.halfHeight * 2;
  73149. result.z = shape.halfDepth * 2;
  73150. };
  73151. OimoJSPlugin.prototype.dispose = function () {
  73152. this.world.clear();
  73153. };
  73154. return OimoJSPlugin;
  73155. }());
  73156. BABYLON.OimoJSPlugin = OimoJSPlugin;
  73157. })(BABYLON || (BABYLON = {}));
  73158. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  73159. var BABYLON;
  73160. (function (BABYLON) {
  73161. /*
  73162. * Based on jsTGALoader - Javascript loader for TGA file
  73163. * By Vincent Thibault
  73164. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  73165. */
  73166. var TGATools = /** @class */ (function () {
  73167. function TGATools() {
  73168. }
  73169. TGATools.GetTGAHeader = function (data) {
  73170. var offset = 0;
  73171. var header = {
  73172. id_length: data[offset++],
  73173. colormap_type: data[offset++],
  73174. image_type: data[offset++],
  73175. colormap_index: data[offset++] | data[offset++] << 8,
  73176. colormap_length: data[offset++] | data[offset++] << 8,
  73177. colormap_size: data[offset++],
  73178. origin: [
  73179. data[offset++] | data[offset++] << 8,
  73180. data[offset++] | data[offset++] << 8
  73181. ],
  73182. width: data[offset++] | data[offset++] << 8,
  73183. height: data[offset++] | data[offset++] << 8,
  73184. pixel_size: data[offset++],
  73185. flags: data[offset++]
  73186. };
  73187. return header;
  73188. };
  73189. TGATools.UploadContent = function (gl, data) {
  73190. // Not enough data to contain header ?
  73191. if (data.length < 19) {
  73192. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  73193. return;
  73194. }
  73195. // Read Header
  73196. var offset = 18;
  73197. var header = TGATools.GetTGAHeader(data);
  73198. // Assume it's a valid Targa file.
  73199. if (header.id_length + offset > data.length) {
  73200. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  73201. return;
  73202. }
  73203. // Skip not needed data
  73204. offset += header.id_length;
  73205. var use_rle = false;
  73206. var use_pal = false;
  73207. var use_grey = false;
  73208. // Get some informations.
  73209. switch (header.image_type) {
  73210. case TGATools._TYPE_RLE_INDEXED:
  73211. use_rle = true;
  73212. case TGATools._TYPE_INDEXED:
  73213. use_pal = true;
  73214. break;
  73215. case TGATools._TYPE_RLE_RGB:
  73216. use_rle = true;
  73217. case TGATools._TYPE_RGB:
  73218. // use_rgb = true;
  73219. break;
  73220. case TGATools._TYPE_RLE_GREY:
  73221. use_rle = true;
  73222. case TGATools._TYPE_GREY:
  73223. use_grey = true;
  73224. break;
  73225. }
  73226. var pixel_data;
  73227. // var numAlphaBits = header.flags & 0xf;
  73228. var pixel_size = header.pixel_size >> 3;
  73229. var pixel_total = header.width * header.height * pixel_size;
  73230. // Read palettes
  73231. var palettes;
  73232. if (use_pal) {
  73233. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  73234. }
  73235. // Read LRE
  73236. if (use_rle) {
  73237. pixel_data = new Uint8Array(pixel_total);
  73238. var c, count, i;
  73239. var localOffset = 0;
  73240. var pixels = new Uint8Array(pixel_size);
  73241. while (offset < pixel_total && localOffset < pixel_total) {
  73242. c = data[offset++];
  73243. count = (c & 0x7f) + 1;
  73244. // RLE pixels
  73245. if (c & 0x80) {
  73246. // Bind pixel tmp array
  73247. for (i = 0; i < pixel_size; ++i) {
  73248. pixels[i] = data[offset++];
  73249. }
  73250. // Copy pixel array
  73251. for (i = 0; i < count; ++i) {
  73252. pixel_data.set(pixels, localOffset + i * pixel_size);
  73253. }
  73254. localOffset += pixel_size * count;
  73255. }
  73256. else {
  73257. count *= pixel_size;
  73258. for (i = 0; i < count; ++i) {
  73259. pixel_data[localOffset + i] = data[offset++];
  73260. }
  73261. localOffset += count;
  73262. }
  73263. }
  73264. }
  73265. else {
  73266. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  73267. }
  73268. // Load to texture
  73269. var x_start, y_start, x_step, y_step, y_end, x_end;
  73270. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  73271. default:
  73272. case TGATools._ORIGIN_UL:
  73273. x_start = 0;
  73274. x_step = 1;
  73275. x_end = header.width;
  73276. y_start = 0;
  73277. y_step = 1;
  73278. y_end = header.height;
  73279. break;
  73280. case TGATools._ORIGIN_BL:
  73281. x_start = 0;
  73282. x_step = 1;
  73283. x_end = header.width;
  73284. y_start = header.height - 1;
  73285. y_step = -1;
  73286. y_end = -1;
  73287. break;
  73288. case TGATools._ORIGIN_UR:
  73289. x_start = header.width - 1;
  73290. x_step = -1;
  73291. x_end = -1;
  73292. y_start = 0;
  73293. y_step = 1;
  73294. y_end = header.height;
  73295. break;
  73296. case TGATools._ORIGIN_BR:
  73297. x_start = header.width - 1;
  73298. x_step = -1;
  73299. x_end = -1;
  73300. y_start = header.height - 1;
  73301. y_step = -1;
  73302. y_end = -1;
  73303. break;
  73304. }
  73305. // Load the specify method
  73306. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  73307. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  73308. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  73309. };
  73310. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73311. var image = pixel_data, colormap = palettes;
  73312. var width = header.width, height = header.height;
  73313. var color, i = 0, x, y;
  73314. var imageData = new Uint8Array(width * height * 4);
  73315. for (y = y_start; y !== y_end; y += y_step) {
  73316. for (x = x_start; x !== x_end; x += x_step, i++) {
  73317. color = image[i];
  73318. imageData[(x + width * y) * 4 + 3] = 255;
  73319. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  73320. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  73321. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  73322. }
  73323. }
  73324. return imageData;
  73325. };
  73326. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73327. var image = pixel_data;
  73328. var width = header.width, height = header.height;
  73329. var color, i = 0, x, y;
  73330. var imageData = new Uint8Array(width * height * 4);
  73331. for (y = y_start; y !== y_end; y += y_step) {
  73332. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73333. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  73334. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  73335. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  73336. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  73337. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  73338. }
  73339. }
  73340. return imageData;
  73341. };
  73342. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73343. var image = pixel_data;
  73344. var width = header.width, height = header.height;
  73345. var i = 0, x, y;
  73346. var imageData = new Uint8Array(width * height * 4);
  73347. for (y = y_start; y !== y_end; y += y_step) {
  73348. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  73349. imageData[(x + width * y) * 4 + 3] = 255;
  73350. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73351. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73352. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73353. }
  73354. }
  73355. return imageData;
  73356. };
  73357. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73358. var image = pixel_data;
  73359. var width = header.width, height = header.height;
  73360. var i = 0, x, y;
  73361. var imageData = new Uint8Array(width * height * 4);
  73362. for (y = y_start; y !== y_end; y += y_step) {
  73363. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  73364. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73365. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  73366. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  73367. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  73368. }
  73369. }
  73370. return imageData;
  73371. };
  73372. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73373. var image = pixel_data;
  73374. var width = header.width, height = header.height;
  73375. var color, i = 0, x, y;
  73376. var imageData = new Uint8Array(width * height * 4);
  73377. for (y = y_start; y !== y_end; y += y_step) {
  73378. for (x = x_start; x !== x_end; x += x_step, i++) {
  73379. color = image[i];
  73380. imageData[(x + width * y) * 4 + 0] = color;
  73381. imageData[(x + width * y) * 4 + 1] = color;
  73382. imageData[(x + width * y) * 4 + 2] = color;
  73383. imageData[(x + width * y) * 4 + 3] = 255;
  73384. }
  73385. }
  73386. return imageData;
  73387. };
  73388. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  73389. var image = pixel_data;
  73390. var width = header.width, height = header.height;
  73391. var i = 0, x, y;
  73392. var imageData = new Uint8Array(width * height * 4);
  73393. for (y = y_start; y !== y_end; y += y_step) {
  73394. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  73395. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  73396. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  73397. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  73398. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  73399. }
  73400. }
  73401. return imageData;
  73402. };
  73403. //private static _TYPE_NO_DATA = 0;
  73404. TGATools._TYPE_INDEXED = 1;
  73405. TGATools._TYPE_RGB = 2;
  73406. TGATools._TYPE_GREY = 3;
  73407. TGATools._TYPE_RLE_INDEXED = 9;
  73408. TGATools._TYPE_RLE_RGB = 10;
  73409. TGATools._TYPE_RLE_GREY = 11;
  73410. TGATools._ORIGIN_MASK = 0x30;
  73411. TGATools._ORIGIN_SHIFT = 0x04;
  73412. TGATools._ORIGIN_BL = 0x00;
  73413. TGATools._ORIGIN_BR = 0x01;
  73414. TGATools._ORIGIN_UL = 0x02;
  73415. TGATools._ORIGIN_UR = 0x03;
  73416. return TGATools;
  73417. }());
  73418. BABYLON.TGATools = TGATools;
  73419. })(BABYLON || (BABYLON = {}));
  73420. //# sourceMappingURL=babylon.tga.js.map
  73421. var BABYLON;
  73422. (function (BABYLON) {
  73423. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  73424. // All values and structures referenced from:
  73425. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  73426. var DDS_MAGIC = 0x20534444;
  73427. var
  73428. //DDSD_CAPS = 0x1,
  73429. //DDSD_HEIGHT = 0x2,
  73430. //DDSD_WIDTH = 0x4,
  73431. //DDSD_PITCH = 0x8,
  73432. //DDSD_PIXELFORMAT = 0x1000,
  73433. DDSD_MIPMAPCOUNT = 0x20000;
  73434. //DDSD_LINEARSIZE = 0x80000,
  73435. //DDSD_DEPTH = 0x800000;
  73436. // var DDSCAPS_COMPLEX = 0x8,
  73437. // DDSCAPS_MIPMAP = 0x400000,
  73438. // DDSCAPS_TEXTURE = 0x1000;
  73439. var DDSCAPS2_CUBEMAP = 0x200;
  73440. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  73441. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  73442. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  73443. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  73444. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  73445. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  73446. // DDSCAPS2_VOLUME = 0x200000;
  73447. var
  73448. //DDPF_ALPHAPIXELS = 0x1,
  73449. //DDPF_ALPHA = 0x2,
  73450. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  73451. //DDPF_YUV = 0x200,
  73452. DDPF_LUMINANCE = 0x20000;
  73453. function FourCCToInt32(value) {
  73454. return value.charCodeAt(0) +
  73455. (value.charCodeAt(1) << 8) +
  73456. (value.charCodeAt(2) << 16) +
  73457. (value.charCodeAt(3) << 24);
  73458. }
  73459. function Int32ToFourCC(value) {
  73460. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  73461. }
  73462. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  73463. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  73464. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  73465. var FOURCC_DX10 = FourCCToInt32("DX10");
  73466. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  73467. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  73468. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  73469. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  73470. var headerLengthInt = 31; // The header length in 32 bit ints
  73471. // Offsets into the header array
  73472. var off_magic = 0;
  73473. var off_size = 1;
  73474. var off_flags = 2;
  73475. var off_height = 3;
  73476. var off_width = 4;
  73477. var off_mipmapCount = 7;
  73478. var off_pfFlags = 20;
  73479. var off_pfFourCC = 21;
  73480. var off_RGBbpp = 22;
  73481. var off_RMask = 23;
  73482. var off_GMask = 24;
  73483. var off_BMask = 25;
  73484. var off_AMask = 26;
  73485. // var off_caps1 = 27;
  73486. var off_caps2 = 28;
  73487. // var off_caps3 = 29;
  73488. // var off_caps4 = 30;
  73489. var off_dxgiFormat = 32;
  73490. ;
  73491. var DDSTools = /** @class */ (function () {
  73492. function DDSTools() {
  73493. }
  73494. DDSTools.GetDDSInfo = function (arrayBuffer) {
  73495. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73496. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  73497. var mipmapCount = 1;
  73498. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  73499. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73500. }
  73501. var fourCC = header[off_pfFourCC];
  73502. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  73503. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73504. switch (fourCC) {
  73505. case FOURCC_D3DFMT_R16G16B16A16F:
  73506. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73507. break;
  73508. case FOURCC_D3DFMT_R32G32B32A32F:
  73509. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73510. break;
  73511. case FOURCC_DX10:
  73512. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  73513. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73514. break;
  73515. }
  73516. }
  73517. return {
  73518. width: header[off_width],
  73519. height: header[off_height],
  73520. mipmapCount: mipmapCount,
  73521. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  73522. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  73523. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  73524. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  73525. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  73526. dxgiFormat: dxgiFormat,
  73527. textureType: textureType
  73528. };
  73529. };
  73530. DDSTools._ToHalfFloat = function (value) {
  73531. if (!DDSTools._FloatView) {
  73532. DDSTools._FloatView = new Float32Array(1);
  73533. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  73534. }
  73535. DDSTools._FloatView[0] = value;
  73536. var x = DDSTools._Int32View[0];
  73537. var bits = (x >> 16) & 0x8000; /* Get the sign */
  73538. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  73539. var e = (x >> 23) & 0xff; /* Using int is faster here */
  73540. /* If zero, or denormal, or exponent underflows too much for a denormal
  73541. * half, return signed zero. */
  73542. if (e < 103) {
  73543. return bits;
  73544. }
  73545. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  73546. if (e > 142) {
  73547. bits |= 0x7c00;
  73548. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  73549. * not Inf, so make sure we set one mantissa bit too. */
  73550. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  73551. return bits;
  73552. }
  73553. /* If exponent underflows but not too much, return a denormal */
  73554. if (e < 113) {
  73555. m |= 0x0800;
  73556. /* Extra rounding may overflow and set mantissa to 0 and exponent
  73557. * to 1, which is OK. */
  73558. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  73559. return bits;
  73560. }
  73561. bits |= ((e - 112) << 10) | (m >> 1);
  73562. bits += m & 1;
  73563. return bits;
  73564. };
  73565. DDSTools._FromHalfFloat = function (value) {
  73566. var s = (value & 0x8000) >> 15;
  73567. var e = (value & 0x7C00) >> 10;
  73568. var f = value & 0x03FF;
  73569. if (e === 0) {
  73570. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  73571. }
  73572. else if (e == 0x1F) {
  73573. return f ? NaN : ((s ? -1 : 1) * Infinity);
  73574. }
  73575. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  73576. };
  73577. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73578. var destArray = new Float32Array(dataLength);
  73579. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73580. var index = 0;
  73581. for (var y = 0; y < height; y++) {
  73582. for (var x = 0; x < width; x++) {
  73583. var srcPos = (x + y * width) * 4;
  73584. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  73585. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  73586. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  73587. if (DDSTools.StoreLODInAlphaChannel) {
  73588. destArray[index + 3] = lod;
  73589. }
  73590. else {
  73591. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  73592. }
  73593. index += 4;
  73594. }
  73595. }
  73596. return destArray;
  73597. };
  73598. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73599. if (DDSTools.StoreLODInAlphaChannel) {
  73600. var destArray = new Uint16Array(dataLength);
  73601. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73602. var index = 0;
  73603. for (var y = 0; y < height; y++) {
  73604. for (var x = 0; x < width; x++) {
  73605. var srcPos = (x + y * width) * 4;
  73606. destArray[index] = srcData[srcPos];
  73607. destArray[index + 1] = srcData[srcPos + 1];
  73608. destArray[index + 2] = srcData[srcPos + 2];
  73609. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  73610. index += 4;
  73611. }
  73612. }
  73613. return destArray;
  73614. }
  73615. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  73616. };
  73617. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73618. if (DDSTools.StoreLODInAlphaChannel) {
  73619. var destArray = new Float32Array(dataLength);
  73620. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73621. var index = 0;
  73622. for (var y = 0; y < height; y++) {
  73623. for (var x = 0; x < width; x++) {
  73624. var srcPos = (x + y * width) * 4;
  73625. destArray[index] = srcData[srcPos];
  73626. destArray[index + 1] = srcData[srcPos + 1];
  73627. destArray[index + 2] = srcData[srcPos + 2];
  73628. destArray[index + 3] = lod;
  73629. index += 4;
  73630. }
  73631. }
  73632. return destArray;
  73633. }
  73634. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  73635. };
  73636. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73637. var destArray = new Uint8Array(dataLength);
  73638. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73639. var index = 0;
  73640. for (var y = 0; y < height; y++) {
  73641. for (var x = 0; x < width; x++) {
  73642. var srcPos = (x + y * width) * 4;
  73643. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  73644. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  73645. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  73646. if (DDSTools.StoreLODInAlphaChannel) {
  73647. destArray[index + 3] = lod;
  73648. }
  73649. else {
  73650. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  73651. }
  73652. index += 4;
  73653. }
  73654. }
  73655. return destArray;
  73656. };
  73657. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73658. var destArray = new Uint8Array(dataLength);
  73659. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73660. var index = 0;
  73661. for (var y = 0; y < height; y++) {
  73662. for (var x = 0; x < width; x++) {
  73663. var srcPos = (x + y * width) * 4;
  73664. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  73665. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  73666. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  73667. if (DDSTools.StoreLODInAlphaChannel) {
  73668. destArray[index + 3] = lod;
  73669. }
  73670. else {
  73671. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  73672. }
  73673. index += 4;
  73674. }
  73675. }
  73676. return destArray;
  73677. };
  73678. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  73679. var byteArray = new Uint8Array(dataLength);
  73680. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73681. var index = 0;
  73682. for (var y = 0; y < height; y++) {
  73683. for (var x = 0; x < width; x++) {
  73684. var srcPos = (x + y * width) * 4;
  73685. byteArray[index] = srcData[srcPos + rOffset];
  73686. byteArray[index + 1] = srcData[srcPos + gOffset];
  73687. byteArray[index + 2] = srcData[srcPos + bOffset];
  73688. byteArray[index + 3] = srcData[srcPos + aOffset];
  73689. index += 4;
  73690. }
  73691. }
  73692. return byteArray;
  73693. };
  73694. DDSTools._ExtractLongWordOrder = function (value) {
  73695. if (value === 0 || value === 255 || value === -16777216) {
  73696. return 0;
  73697. }
  73698. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  73699. };
  73700. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  73701. var byteArray = new Uint8Array(dataLength);
  73702. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73703. var index = 0;
  73704. for (var y = 0; y < height; y++) {
  73705. for (var x = 0; x < width; x++) {
  73706. var srcPos = (x + y * width) * 3;
  73707. byteArray[index] = srcData[srcPos + rOffset];
  73708. byteArray[index + 1] = srcData[srcPos + gOffset];
  73709. byteArray[index + 2] = srcData[srcPos + bOffset];
  73710. index += 3;
  73711. }
  73712. }
  73713. return byteArray;
  73714. };
  73715. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  73716. var byteArray = new Uint8Array(dataLength);
  73717. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73718. var index = 0;
  73719. for (var y = 0; y < height; y++) {
  73720. for (var x = 0; x < width; x++) {
  73721. var srcPos = (x + y * width);
  73722. byteArray[index] = srcData[srcPos];
  73723. index++;
  73724. }
  73725. }
  73726. return byteArray;
  73727. };
  73728. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  73729. if (lodIndex === void 0) { lodIndex = -1; }
  73730. var ext = engine.getCaps().s3tc;
  73731. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73732. var fourCC, width, height, dataLength = 0, dataOffset;
  73733. var byteArray, mipmapCount, mip;
  73734. var internalFormat = 0;
  73735. var format = 0;
  73736. var blockBytes = 1;
  73737. if (header[off_magic] !== DDS_MAGIC) {
  73738. BABYLON.Tools.Error("Invalid magic number in DDS header");
  73739. return;
  73740. }
  73741. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  73742. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  73743. return;
  73744. }
  73745. if (info.isCompressed && !ext) {
  73746. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  73747. return;
  73748. }
  73749. var bpp = header[off_RGBbpp];
  73750. dataOffset = header[off_size] + 4;
  73751. var computeFormats = false;
  73752. if (info.isFourCC) {
  73753. fourCC = header[off_pfFourCC];
  73754. switch (fourCC) {
  73755. case FOURCC_DXT1:
  73756. blockBytes = 8;
  73757. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  73758. break;
  73759. case FOURCC_DXT3:
  73760. blockBytes = 16;
  73761. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  73762. break;
  73763. case FOURCC_DXT5:
  73764. blockBytes = 16;
  73765. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  73766. break;
  73767. case FOURCC_D3DFMT_R16G16B16A16F:
  73768. computeFormats = true;
  73769. break;
  73770. case FOURCC_D3DFMT_R32G32B32A32F:
  73771. computeFormats = true;
  73772. break;
  73773. case FOURCC_DX10:
  73774. // There is an additionnal header so dataOffset need to be changed
  73775. dataOffset += 5 * 4; // 5 uints
  73776. var supported = false;
  73777. switch (info.dxgiFormat) {
  73778. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  73779. computeFormats = true;
  73780. supported = true;
  73781. break;
  73782. case DXGI_FORMAT_B8G8R8X8_UNORM:
  73783. info.isRGB = true;
  73784. info.isFourCC = false;
  73785. bpp = 32;
  73786. supported = true;
  73787. break;
  73788. }
  73789. if (supported) {
  73790. break;
  73791. }
  73792. default:
  73793. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  73794. return;
  73795. }
  73796. }
  73797. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  73798. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  73799. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  73800. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  73801. if (computeFormats) {
  73802. format = engine._getWebGLTextureType(info.textureType);
  73803. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73804. }
  73805. mipmapCount = 1;
  73806. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  73807. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73808. }
  73809. for (var face = 0; face < faces; face++) {
  73810. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  73811. width = header[off_width];
  73812. height = header[off_height];
  73813. for (mip = 0; mip < mipmapCount; ++mip) {
  73814. if (lodIndex === -1 || lodIndex === mip) {
  73815. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  73816. var i = (lodIndex === -1) ? mip : 0;
  73817. if (!info.isCompressed && info.isFourCC) {
  73818. dataLength = width * height * 4;
  73819. var floatArray = null;
  73820. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  73821. if (bpp === 128) {
  73822. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73823. }
  73824. else if (bpp === 64) {
  73825. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73826. }
  73827. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73828. format = engine._getWebGLTextureType(info.textureType);
  73829. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73830. }
  73831. else {
  73832. if (bpp === 128) {
  73833. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73834. }
  73835. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  73836. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73837. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73838. format = engine._getWebGLTextureType(info.textureType);
  73839. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73840. }
  73841. else {
  73842. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73843. }
  73844. }
  73845. if (floatArray) {
  73846. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  73847. }
  73848. }
  73849. else if (info.isRGB) {
  73850. if (bpp === 24) {
  73851. dataLength = width * height * 3;
  73852. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  73853. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  73854. }
  73855. else {
  73856. dataLength = width * height * 4;
  73857. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  73858. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  73859. }
  73860. }
  73861. else if (info.isLuminance) {
  73862. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  73863. var unpaddedRowSize = width;
  73864. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  73865. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  73866. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  73867. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  73868. }
  73869. else {
  73870. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  73871. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  73872. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  73873. }
  73874. }
  73875. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  73876. width *= 0.5;
  73877. height *= 0.5;
  73878. width = Math.max(1.0, width);
  73879. height = Math.max(1.0, height);
  73880. }
  73881. if (currentFace !== undefined) {
  73882. // Loading a single face
  73883. break;
  73884. }
  73885. }
  73886. };
  73887. DDSTools.StoreLODInAlphaChannel = false;
  73888. return DDSTools;
  73889. }());
  73890. BABYLON.DDSTools = DDSTools;
  73891. })(BABYLON || (BABYLON = {}));
  73892. //# sourceMappingURL=babylon.dds.js.map
  73893. var BABYLON;
  73894. (function (BABYLON) {
  73895. /**
  73896. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  73897. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  73898. */
  73899. var KhronosTextureContainer = /** @class */ (function () {
  73900. /**
  73901. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  73902. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  73903. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  73904. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  73905. */
  73906. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  73907. this.arrayBuffer = arrayBuffer;
  73908. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  73909. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  73910. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  73911. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  73912. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  73913. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  73914. BABYLON.Tools.Error("texture missing KTX identifier");
  73915. return;
  73916. }
  73917. // load the reset of the header in native 32 bit int
  73918. var header = new Int32Array(this.arrayBuffer, 12, 13);
  73919. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  73920. var oppositeEndianess = header[0] === 0x01020304;
  73921. // read all the header elements in order they exist in the file, without modification (sans endainness)
  73922. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  73923. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  73924. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  73925. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  73926. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  73927. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  73928. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  73929. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  73930. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  73931. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  73932. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  73933. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  73934. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  73935. if (this.glType !== 0) {
  73936. BABYLON.Tools.Error("only compressed formats currently supported");
  73937. return;
  73938. }
  73939. else {
  73940. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  73941. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  73942. }
  73943. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  73944. BABYLON.Tools.Error("only 2D textures currently supported");
  73945. return;
  73946. }
  73947. if (this.numberOfArrayElements !== 0) {
  73948. BABYLON.Tools.Error("texture arrays not currently supported");
  73949. return;
  73950. }
  73951. if (this.numberOfFaces !== facesExpected) {
  73952. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  73953. return;
  73954. }
  73955. // we now have a completely validated file, so could use existence of loadType as success
  73956. // would need to make this more elaborate & adjust checks above to support more than one load type
  73957. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  73958. }
  73959. // not as fast hardware based, but will probably never need to use
  73960. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  73961. return ((val & 0xFF) << 24)
  73962. | ((val & 0xFF00) << 8)
  73963. | ((val >> 8) & 0xFF00)
  73964. | ((val >> 24) & 0xFF);
  73965. };
  73966. /**
  73967. * It is assumed that the texture has already been created & is currently bound
  73968. */
  73969. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  73970. switch (this.loadType) {
  73971. case KhronosTextureContainer.COMPRESSED_2D:
  73972. this._upload2DCompressedLevels(gl, loadMipmaps);
  73973. break;
  73974. case KhronosTextureContainer.TEX_2D:
  73975. case KhronosTextureContainer.COMPRESSED_3D:
  73976. case KhronosTextureContainer.TEX_3D:
  73977. }
  73978. };
  73979. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  73980. // initialize width & height for level 1
  73981. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  73982. var width = this.pixelWidth;
  73983. var height = this.pixelHeight;
  73984. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  73985. for (var level = 0; level < mipmapCount; level++) {
  73986. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  73987. for (var face = 0; face < this.numberOfFaces; face++) {
  73988. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  73989. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  73990. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  73991. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  73992. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  73993. }
  73994. width = Math.max(1.0, width * 0.5);
  73995. height = Math.max(1.0, height * 0.5);
  73996. }
  73997. };
  73998. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  73999. // load types
  74000. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  74001. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  74002. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  74003. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  74004. return KhronosTextureContainer;
  74005. }());
  74006. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  74007. })(BABYLON || (BABYLON = {}));
  74008. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  74009. var BABYLON;
  74010. (function (BABYLON) {
  74011. var Debug = /** @class */ (function () {
  74012. function Debug() {
  74013. }
  74014. Debug.AxesViewer = /** @class */ (function () {
  74015. function AxesViewer(scene, scaleLines) {
  74016. if (scaleLines === void 0) { scaleLines = 1; }
  74017. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74018. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74019. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74020. this.scaleLines = 1;
  74021. this.scaleLines = scaleLines;
  74022. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  74023. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  74024. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  74025. this._xmesh.renderingGroupId = 2;
  74026. this._ymesh.renderingGroupId = 2;
  74027. this._zmesh.renderingGroupId = 2;
  74028. this._xmesh.material.checkReadyOnlyOnce = true;
  74029. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  74030. this._ymesh.material.checkReadyOnlyOnce = true;
  74031. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  74032. this._zmesh.material.checkReadyOnlyOnce = true;
  74033. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  74034. this.scene = scene;
  74035. }
  74036. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  74037. var scaleLines = this.scaleLines;
  74038. if (this._xmesh) {
  74039. this._xmesh.position.copyFrom(position);
  74040. }
  74041. if (this._ymesh) {
  74042. this._ymesh.position.copyFrom(position);
  74043. }
  74044. if (this._zmesh) {
  74045. this._zmesh.position.copyFrom(position);
  74046. }
  74047. var point2 = this._xline[1];
  74048. point2.x = xaxis.x * scaleLines;
  74049. point2.y = xaxis.y * scaleLines;
  74050. point2.z = xaxis.z * scaleLines;
  74051. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  74052. point2 = this._yline[1];
  74053. point2.x = yaxis.x * scaleLines;
  74054. point2.y = yaxis.y * scaleLines;
  74055. point2.z = yaxis.z * scaleLines;
  74056. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  74057. point2 = this._zline[1];
  74058. point2.x = zaxis.x * scaleLines;
  74059. point2.y = zaxis.y * scaleLines;
  74060. point2.z = zaxis.z * scaleLines;
  74061. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  74062. };
  74063. AxesViewer.prototype.dispose = function () {
  74064. if (this._xmesh) {
  74065. this._xmesh.dispose();
  74066. }
  74067. if (this._ymesh) {
  74068. this._ymesh.dispose();
  74069. }
  74070. if (this._zmesh) {
  74071. this._zmesh.dispose();
  74072. }
  74073. this._xmesh = null;
  74074. this._ymesh = null;
  74075. this._zmesh = null;
  74076. this.scene = null;
  74077. };
  74078. return AxesViewer;
  74079. }());
  74080. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  74081. __extends(BoneAxesViewer, _super);
  74082. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  74083. if (scaleLines === void 0) { scaleLines = 1; }
  74084. var _this = _super.call(this, scene, scaleLines) || this;
  74085. _this.pos = BABYLON.Vector3.Zero();
  74086. _this.xaxis = BABYLON.Vector3.Zero();
  74087. _this.yaxis = BABYLON.Vector3.Zero();
  74088. _this.zaxis = BABYLON.Vector3.Zero();
  74089. _this.mesh = mesh;
  74090. _this.bone = bone;
  74091. return _this;
  74092. }
  74093. BoneAxesViewer.prototype.update = function () {
  74094. if (!this.mesh || !this.bone) {
  74095. return;
  74096. }
  74097. var bone = this.bone;
  74098. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  74099. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  74100. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  74101. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  74102. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  74103. };
  74104. BoneAxesViewer.prototype.dispose = function () {
  74105. if (this.mesh) {
  74106. this.mesh = null;
  74107. this.bone = null;
  74108. _super.prototype.dispose.call(this);
  74109. }
  74110. };
  74111. return BoneAxesViewer;
  74112. }(Debug.AxesViewer));
  74113. Debug.PhysicsViewer = /** @class */ (function () {
  74114. function PhysicsViewer(scene) {
  74115. this._impostors = [];
  74116. this._meshes = [];
  74117. this._numMeshes = 0;
  74118. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74119. var physicEngine = this._scene.getPhysicsEngine();
  74120. if (physicEngine) {
  74121. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  74122. }
  74123. }
  74124. PhysicsViewer.prototype._updateDebugMeshes = function () {
  74125. var plugin = this._physicsEnginePlugin;
  74126. for (var i = 0; i < this._numMeshes; i++) {
  74127. var impostor = this._impostors[i];
  74128. if (!impostor) {
  74129. continue;
  74130. }
  74131. if (impostor.isDisposed) {
  74132. this.hideImpostor(this._impostors[i--]);
  74133. }
  74134. else {
  74135. var mesh = this._meshes[i];
  74136. if (mesh && plugin) {
  74137. plugin.syncMeshWithImpostor(mesh, impostor);
  74138. }
  74139. }
  74140. }
  74141. };
  74142. PhysicsViewer.prototype.showImpostor = function (impostor) {
  74143. if (!this._scene) {
  74144. return;
  74145. }
  74146. for (var i = 0; i < this._numMeshes; i++) {
  74147. if (this._impostors[i] == impostor) {
  74148. return;
  74149. }
  74150. }
  74151. var debugMesh = this._getDebugMesh(impostor, this._scene);
  74152. if (debugMesh) {
  74153. this._impostors[this._numMeshes] = impostor;
  74154. this._meshes[this._numMeshes] = debugMesh;
  74155. if (this._numMeshes === 0) {
  74156. this._renderFunction = this._updateDebugMeshes.bind(this);
  74157. this._scene.registerBeforeRender(this._renderFunction);
  74158. }
  74159. this._numMeshes++;
  74160. }
  74161. };
  74162. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  74163. if (!impostor || !this._scene) {
  74164. return;
  74165. }
  74166. var removed = false;
  74167. for (var i = 0; i < this._numMeshes; i++) {
  74168. if (this._impostors[i] == impostor) {
  74169. var mesh = this._meshes[i];
  74170. if (!mesh) {
  74171. continue;
  74172. }
  74173. this._scene.removeMesh(mesh);
  74174. mesh.dispose();
  74175. this._numMeshes--;
  74176. if (this._numMeshes > 0) {
  74177. this._meshes[i] = this._meshes[this._numMeshes];
  74178. this._impostors[i] = this._impostors[this._numMeshes];
  74179. this._meshes[this._numMeshes] = null;
  74180. this._impostors[this._numMeshes] = null;
  74181. }
  74182. else {
  74183. this._meshes[0] = null;
  74184. this._impostors[0] = null;
  74185. }
  74186. removed = true;
  74187. break;
  74188. }
  74189. }
  74190. if (removed && this._numMeshes === 0) {
  74191. this._scene.unregisterBeforeRender(this._renderFunction);
  74192. }
  74193. };
  74194. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  74195. if (!this._debugMaterial) {
  74196. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  74197. this._debugMaterial.wireframe = true;
  74198. }
  74199. return this._debugMaterial;
  74200. };
  74201. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  74202. if (!this._debugBoxMesh) {
  74203. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  74204. this._debugBoxMesh.renderingGroupId = 1;
  74205. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74206. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  74207. scene.removeMesh(this._debugBoxMesh);
  74208. }
  74209. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  74210. };
  74211. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  74212. if (!this._debugSphereMesh) {
  74213. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  74214. this._debugSphereMesh.renderingGroupId = 1;
  74215. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  74216. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  74217. scene.removeMesh(this._debugSphereMesh);
  74218. }
  74219. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  74220. };
  74221. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  74222. var mesh = null;
  74223. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  74224. mesh = this._getDebugBoxMesh(scene);
  74225. impostor.getBoxSizeToRef(mesh.scaling);
  74226. }
  74227. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  74228. mesh = this._getDebugSphereMesh(scene);
  74229. var radius = impostor.getRadius();
  74230. mesh.scaling.x = radius * 2;
  74231. mesh.scaling.y = radius * 2;
  74232. mesh.scaling.z = radius * 2;
  74233. }
  74234. return mesh;
  74235. };
  74236. PhysicsViewer.prototype.dispose = function () {
  74237. for (var i = 0; i < this._numMeshes; i++) {
  74238. this.hideImpostor(this._impostors[i]);
  74239. }
  74240. if (this._debugBoxMesh) {
  74241. this._debugBoxMesh.dispose();
  74242. }
  74243. if (this._debugSphereMesh) {
  74244. this._debugSphereMesh.dispose();
  74245. }
  74246. if (this._debugMaterial) {
  74247. this._debugMaterial.dispose();
  74248. }
  74249. this._impostors.length = 0;
  74250. this._scene = null;
  74251. this._physicsEnginePlugin = null;
  74252. };
  74253. return PhysicsViewer;
  74254. }());
  74255. Debug.SkeletonViewer = /** @class */ (function () {
  74256. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  74257. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  74258. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  74259. this.skeleton = skeleton;
  74260. this.mesh = mesh;
  74261. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  74262. this.renderingGroupId = renderingGroupId;
  74263. this.color = BABYLON.Color3.White();
  74264. this._debugLines = new Array();
  74265. this._isEnabled = false;
  74266. this._scene = scene;
  74267. this.update();
  74268. this._renderFunction = this.update.bind(this);
  74269. }
  74270. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  74271. get: function () {
  74272. return this._isEnabled;
  74273. },
  74274. set: function (value) {
  74275. if (this._isEnabled === value) {
  74276. return;
  74277. }
  74278. this._isEnabled = value;
  74279. if (value) {
  74280. this._scene.registerBeforeRender(this._renderFunction);
  74281. }
  74282. else {
  74283. this._scene.unregisterBeforeRender(this._renderFunction);
  74284. }
  74285. },
  74286. enumerable: true,
  74287. configurable: true
  74288. });
  74289. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  74290. if (x === void 0) { x = 0; }
  74291. if (y === void 0) { y = 0; }
  74292. if (z === void 0) { z = 0; }
  74293. var tmat = BABYLON.Tmp.Matrix[0];
  74294. var parentBone = bone.getParent();
  74295. tmat.copyFrom(bone.getLocalMatrix());
  74296. if (x !== 0 || y !== 0 || z !== 0) {
  74297. var tmat2 = BABYLON.Tmp.Matrix[1];
  74298. BABYLON.Matrix.IdentityToRef(tmat2);
  74299. tmat2.m[12] = x;
  74300. tmat2.m[13] = y;
  74301. tmat2.m[14] = z;
  74302. tmat2.multiplyToRef(tmat, tmat);
  74303. }
  74304. if (parentBone) {
  74305. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  74306. }
  74307. tmat.multiplyToRef(meshMat, tmat);
  74308. position.x = tmat.m[12];
  74309. position.y = tmat.m[13];
  74310. position.z = tmat.m[14];
  74311. };
  74312. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  74313. var len = bones.length;
  74314. var meshPos = this.mesh.position;
  74315. for (var i = 0; i < len; i++) {
  74316. var bone = bones[i];
  74317. var points = this._debugLines[i];
  74318. if (!points) {
  74319. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74320. this._debugLines[i] = points;
  74321. }
  74322. this._getBonePosition(points[0], bone, meshMat);
  74323. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  74324. points[0].subtractInPlace(meshPos);
  74325. points[1].subtractInPlace(meshPos);
  74326. }
  74327. };
  74328. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  74329. var len = bones.length;
  74330. var boneNum = 0;
  74331. var meshPos = this.mesh.position;
  74332. for (var i = len - 1; i >= 0; i--) {
  74333. var childBone = bones[i];
  74334. var parentBone = childBone.getParent();
  74335. if (!parentBone) {
  74336. continue;
  74337. }
  74338. var points = this._debugLines[boneNum];
  74339. if (!points) {
  74340. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74341. this._debugLines[boneNum] = points;
  74342. }
  74343. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  74344. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  74345. points[0].subtractInPlace(meshPos);
  74346. points[1].subtractInPlace(meshPos);
  74347. boneNum++;
  74348. }
  74349. };
  74350. SkeletonViewer.prototype.update = function () {
  74351. if (this.autoUpdateBonesMatrices) {
  74352. this.skeleton.computeAbsoluteTransforms();
  74353. }
  74354. if (this.skeleton.bones[0].length === undefined) {
  74355. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74356. }
  74357. else {
  74358. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  74359. }
  74360. if (!this._debugMesh) {
  74361. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  74362. this._debugMesh.renderingGroupId = this.renderingGroupId;
  74363. }
  74364. else {
  74365. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  74366. }
  74367. this._debugMesh.position.copyFrom(this.mesh.position);
  74368. this._debugMesh.color = this.color;
  74369. };
  74370. SkeletonViewer.prototype.dispose = function () {
  74371. if (this._debugMesh) {
  74372. this.isEnabled = false;
  74373. this._debugMesh.dispose();
  74374. this._debugMesh = null;
  74375. }
  74376. };
  74377. return SkeletonViewer;
  74378. }());
  74379. return Debug;
  74380. }());
  74381. BABYLON.Debug = Debug;
  74382. })(BABYLON || (BABYLON = {}));
  74383. //# sourceMappingURL=babylon.debugModules.js.map
  74384. var BABYLON;
  74385. (function (BABYLON) {
  74386. var RayHelper = /** @class */ (function () {
  74387. function RayHelper(ray) {
  74388. this.ray = ray;
  74389. }
  74390. RayHelper.CreateAndShow = function (ray, scene, color) {
  74391. var helper = new RayHelper(ray);
  74392. helper.show(scene, color);
  74393. return helper;
  74394. };
  74395. RayHelper.prototype.show = function (scene, color) {
  74396. if (!this._renderFunction && this.ray) {
  74397. var ray = this.ray;
  74398. this._renderFunction = this._render.bind(this);
  74399. this._scene = scene;
  74400. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  74401. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  74402. if (this._renderFunction) {
  74403. this._scene.registerBeforeRender(this._renderFunction);
  74404. }
  74405. }
  74406. if (color && this._renderLine) {
  74407. this._renderLine.color.copyFrom(color);
  74408. }
  74409. };
  74410. RayHelper.prototype.hide = function () {
  74411. if (this._renderFunction && this._scene) {
  74412. this._scene.unregisterBeforeRender(this._renderFunction);
  74413. this._scene = null;
  74414. this._renderFunction = null;
  74415. if (this._renderLine) {
  74416. this._renderLine.dispose();
  74417. this._renderLine = null;
  74418. }
  74419. this._renderPoints = [];
  74420. }
  74421. };
  74422. RayHelper.prototype._render = function () {
  74423. var ray = this.ray;
  74424. if (!ray) {
  74425. return;
  74426. }
  74427. var point = this._renderPoints[1];
  74428. var len = Math.min(ray.length, 1000000);
  74429. point.copyFrom(ray.direction);
  74430. point.scaleInPlace(len);
  74431. point.addInPlace(ray.origin);
  74432. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  74433. };
  74434. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  74435. this._attachedToMesh = mesh;
  74436. var ray = this.ray;
  74437. if (!ray) {
  74438. return;
  74439. }
  74440. if (!ray.direction) {
  74441. ray.direction = BABYLON.Vector3.Zero();
  74442. }
  74443. if (!ray.origin) {
  74444. ray.origin = BABYLON.Vector3.Zero();
  74445. }
  74446. if (length) {
  74447. ray.length = length;
  74448. }
  74449. if (!meshSpaceOrigin) {
  74450. meshSpaceOrigin = BABYLON.Vector3.Zero();
  74451. }
  74452. if (!meshSpaceDirection) {
  74453. // -1 so that this will work with Mesh.lookAt
  74454. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  74455. }
  74456. if (!this._meshSpaceDirection) {
  74457. this._meshSpaceDirection = meshSpaceDirection.clone();
  74458. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  74459. }
  74460. else {
  74461. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  74462. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  74463. }
  74464. if (!this._updateToMeshFunction) {
  74465. this._updateToMeshFunction = this._updateToMesh.bind(this);
  74466. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  74467. }
  74468. this._updateToMesh();
  74469. };
  74470. RayHelper.prototype.detachFromMesh = function () {
  74471. if (this._attachedToMesh) {
  74472. if (this._updateToMeshFunction) {
  74473. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  74474. }
  74475. this._attachedToMesh = null;
  74476. this._updateToMeshFunction = null;
  74477. }
  74478. };
  74479. RayHelper.prototype._updateToMesh = function () {
  74480. var ray = this.ray;
  74481. if (!this._attachedToMesh || !ray) {
  74482. return;
  74483. }
  74484. if (this._attachedToMesh._isDisposed) {
  74485. this.detachFromMesh();
  74486. return;
  74487. }
  74488. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  74489. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  74490. };
  74491. RayHelper.prototype.dispose = function () {
  74492. this.hide();
  74493. this.detachFromMesh();
  74494. this.ray = null;
  74495. };
  74496. return RayHelper;
  74497. }());
  74498. BABYLON.RayHelper = RayHelper;
  74499. })(BABYLON || (BABYLON = {}));
  74500. //# sourceMappingURL=babylon.rayHelper.js.map
  74501. var BABYLON;
  74502. (function (BABYLON) {
  74503. // load the inspector using require, if not present in the global namespace.
  74504. var DebugLayer = /** @class */ (function () {
  74505. function DebugLayer(scene) {
  74506. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74507. this._scene = scene;
  74508. // load inspector using require, if it doesn't exist on the global namespace.
  74509. }
  74510. /** Creates the inspector window. */
  74511. DebugLayer.prototype._createInspector = function (config) {
  74512. if (config === void 0) { config = {}; }
  74513. var popup = config.popup || false;
  74514. var initialTab = config.initialTab || 0;
  74515. var parentElement = config.parentElement || null;
  74516. if (!this._inspector) {
  74517. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  74518. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  74519. } // else nothing to do,; instance is already existing
  74520. };
  74521. DebugLayer.prototype.isVisible = function () {
  74522. if (!this._inspector) {
  74523. return false;
  74524. }
  74525. return true;
  74526. };
  74527. DebugLayer.prototype.hide = function () {
  74528. if (this._inspector) {
  74529. try {
  74530. this._inspector.dispose();
  74531. }
  74532. catch (e) {
  74533. // If the inspector has been removed directly from the inspector tool
  74534. }
  74535. this._inspector = null;
  74536. }
  74537. };
  74538. DebugLayer.prototype.show = function (config) {
  74539. if (config === void 0) { config = {}; }
  74540. if (typeof this.BJSINSPECTOR == 'undefined') {
  74541. // Load inspector and add it to the DOM
  74542. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  74543. }
  74544. else {
  74545. // Otherwise creates the inspector
  74546. this._createInspector(config);
  74547. }
  74548. };
  74549. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  74550. return DebugLayer;
  74551. }());
  74552. BABYLON.DebugLayer = DebugLayer;
  74553. })(BABYLON || (BABYLON = {}));
  74554. //# sourceMappingURL=babylon.debugLayer.js.map
  74555. var BABYLON;
  74556. (function (BABYLON) {
  74557. var BoundingBoxRenderer = /** @class */ (function () {
  74558. function BoundingBoxRenderer(scene) {
  74559. this.frontColor = new BABYLON.Color3(1, 1, 1);
  74560. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  74561. this.showBackLines = true;
  74562. this.renderList = new BABYLON.SmartArray(32);
  74563. this._vertexBuffers = {};
  74564. this._scene = scene;
  74565. }
  74566. BoundingBoxRenderer.prototype._prepareRessources = function () {
  74567. if (this._colorShader) {
  74568. return;
  74569. }
  74570. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  74571. attributes: [BABYLON.VertexBuffer.PositionKind],
  74572. uniforms: ["world", "viewProjection", "color"]
  74573. });
  74574. var engine = this._scene.getEngine();
  74575. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  74576. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  74577. this._createIndexBuffer();
  74578. };
  74579. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  74580. var engine = this._scene.getEngine();
  74581. 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]);
  74582. };
  74583. BoundingBoxRenderer.prototype._rebuild = function () {
  74584. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74585. if (vb) {
  74586. vb._rebuild();
  74587. }
  74588. this._createIndexBuffer();
  74589. };
  74590. BoundingBoxRenderer.prototype.reset = function () {
  74591. this.renderList.reset();
  74592. };
  74593. BoundingBoxRenderer.prototype.render = function () {
  74594. if (this.renderList.length === 0) {
  74595. return;
  74596. }
  74597. this._prepareRessources();
  74598. if (!this._colorShader.isReady()) {
  74599. return;
  74600. }
  74601. var engine = this._scene.getEngine();
  74602. engine.setDepthWrite(false);
  74603. this._colorShader._preBind();
  74604. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  74605. var boundingBox = this.renderList.data[boundingBoxIndex];
  74606. var min = boundingBox.minimum;
  74607. var max = boundingBox.maximum;
  74608. var diff = max.subtract(min);
  74609. var median = min.add(diff.scale(0.5));
  74610. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  74611. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  74612. .multiply(boundingBox.getWorldMatrix());
  74613. // VBOs
  74614. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74615. if (this.showBackLines) {
  74616. // Back
  74617. engine.setDepthFunctionToGreaterOrEqual();
  74618. this._scene.resetCachedMaterial();
  74619. this._colorShader.setColor4("color", this.backColor.toColor4());
  74620. this._colorShader.bind(worldMatrix);
  74621. // Draw order
  74622. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74623. }
  74624. // Front
  74625. engine.setDepthFunctionToLess();
  74626. this._scene.resetCachedMaterial();
  74627. this._colorShader.setColor4("color", this.frontColor.toColor4());
  74628. this._colorShader.bind(worldMatrix);
  74629. // Draw order
  74630. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74631. }
  74632. this._colorShader.unbind();
  74633. engine.setDepthFunctionToLessOrEqual();
  74634. engine.setDepthWrite(true);
  74635. };
  74636. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  74637. this._prepareRessources();
  74638. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  74639. return;
  74640. }
  74641. var engine = this._scene.getEngine();
  74642. engine.setDepthWrite(false);
  74643. engine.setColorWrite(false);
  74644. this._colorShader._preBind();
  74645. var boundingBox = mesh._boundingInfo.boundingBox;
  74646. var min = boundingBox.minimum;
  74647. var max = boundingBox.maximum;
  74648. var diff = max.subtract(min);
  74649. var median = min.add(diff.scale(0.5));
  74650. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  74651. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  74652. .multiply(boundingBox.getWorldMatrix());
  74653. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74654. engine.setDepthFunctionToLess();
  74655. this._scene.resetCachedMaterial();
  74656. this._colorShader.bind(worldMatrix);
  74657. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74658. this._colorShader.unbind();
  74659. engine.setDepthFunctionToLessOrEqual();
  74660. engine.setDepthWrite(true);
  74661. engine.setColorWrite(true);
  74662. };
  74663. BoundingBoxRenderer.prototype.dispose = function () {
  74664. if (!this._colorShader) {
  74665. return;
  74666. }
  74667. this.renderList.dispose();
  74668. this._colorShader.dispose();
  74669. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74670. if (buffer) {
  74671. buffer.dispose();
  74672. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74673. }
  74674. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74675. };
  74676. return BoundingBoxRenderer;
  74677. }());
  74678. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  74679. })(BABYLON || (BABYLON = {}));
  74680. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  74681. var BABYLON;
  74682. (function (BABYLON) {
  74683. var MorphTarget = /** @class */ (function () {
  74684. function MorphTarget(name, influence) {
  74685. if (influence === void 0) { influence = 0; }
  74686. this.name = name;
  74687. this.animations = new Array();
  74688. this._positions = null;
  74689. this._normals = null;
  74690. this._tangents = null;
  74691. this.onInfluenceChanged = new BABYLON.Observable();
  74692. this.influence = influence;
  74693. }
  74694. Object.defineProperty(MorphTarget.prototype, "influence", {
  74695. get: function () {
  74696. return this._influence;
  74697. },
  74698. set: function (influence) {
  74699. if (this._influence === influence) {
  74700. return;
  74701. }
  74702. var previous = this._influence;
  74703. this._influence = influence;
  74704. if (this.onInfluenceChanged.hasObservers) {
  74705. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  74706. }
  74707. },
  74708. enumerable: true,
  74709. configurable: true
  74710. });
  74711. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  74712. get: function () {
  74713. return !!this._positions;
  74714. },
  74715. enumerable: true,
  74716. configurable: true
  74717. });
  74718. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  74719. get: function () {
  74720. return !!this._normals;
  74721. },
  74722. enumerable: true,
  74723. configurable: true
  74724. });
  74725. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  74726. get: function () {
  74727. return !!this._tangents;
  74728. },
  74729. enumerable: true,
  74730. configurable: true
  74731. });
  74732. MorphTarget.prototype.setPositions = function (data) {
  74733. this._positions = data;
  74734. };
  74735. MorphTarget.prototype.getPositions = function () {
  74736. return this._positions;
  74737. };
  74738. MorphTarget.prototype.setNormals = function (data) {
  74739. this._normals = data;
  74740. };
  74741. MorphTarget.prototype.getNormals = function () {
  74742. return this._normals;
  74743. };
  74744. MorphTarget.prototype.setTangents = function (data) {
  74745. this._tangents = data;
  74746. };
  74747. MorphTarget.prototype.getTangents = function () {
  74748. return this._tangents;
  74749. };
  74750. /**
  74751. * Serializes the current target into a Serialization object.
  74752. * Returns the serialized object.
  74753. */
  74754. MorphTarget.prototype.serialize = function () {
  74755. var serializationObject = {};
  74756. serializationObject.name = this.name;
  74757. serializationObject.influence = this.influence;
  74758. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  74759. if (this.hasNormals) {
  74760. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  74761. }
  74762. if (this.hasTangents) {
  74763. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  74764. }
  74765. // Animations
  74766. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  74767. return serializationObject;
  74768. };
  74769. // Statics
  74770. MorphTarget.Parse = function (serializationObject) {
  74771. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  74772. result.setPositions(serializationObject.positions);
  74773. if (serializationObject.normals) {
  74774. result.setNormals(serializationObject.normals);
  74775. }
  74776. if (serializationObject.tangents) {
  74777. result.setTangents(serializationObject.tangents);
  74778. }
  74779. // Animations
  74780. if (serializationObject.animations) {
  74781. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  74782. var parsedAnimation = serializationObject.animations[animationIndex];
  74783. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  74784. }
  74785. }
  74786. return result;
  74787. };
  74788. MorphTarget.FromMesh = function (mesh, name, influence) {
  74789. if (!name) {
  74790. name = mesh.name;
  74791. }
  74792. var result = new MorphTarget(name, influence);
  74793. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74795. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  74796. }
  74797. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  74798. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  74799. }
  74800. return result;
  74801. };
  74802. return MorphTarget;
  74803. }());
  74804. BABYLON.MorphTarget = MorphTarget;
  74805. })(BABYLON || (BABYLON = {}));
  74806. //# sourceMappingURL=babylon.morphTarget.js.map
  74807. var BABYLON;
  74808. (function (BABYLON) {
  74809. var MorphTargetManager = /** @class */ (function () {
  74810. function MorphTargetManager(scene) {
  74811. if (scene === void 0) { scene = null; }
  74812. this._targets = new Array();
  74813. this._targetObservable = new Array();
  74814. this._activeTargets = new BABYLON.SmartArray(16);
  74815. this._supportsNormals = false;
  74816. this._supportsTangents = false;
  74817. this._vertexCount = 0;
  74818. this._uniqueId = 0;
  74819. this._tempInfluences = new Array();
  74820. if (!scene) {
  74821. scene = BABYLON.Engine.LastCreatedScene;
  74822. }
  74823. this._scene = scene;
  74824. if (this._scene) {
  74825. this._scene.morphTargetManagers.push(this);
  74826. this._uniqueId = this._scene.getUniqueId();
  74827. }
  74828. }
  74829. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  74830. get: function () {
  74831. return this._uniqueId;
  74832. },
  74833. enumerable: true,
  74834. configurable: true
  74835. });
  74836. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  74837. get: function () {
  74838. return this._vertexCount;
  74839. },
  74840. enumerable: true,
  74841. configurable: true
  74842. });
  74843. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  74844. get: function () {
  74845. return this._supportsNormals;
  74846. },
  74847. enumerable: true,
  74848. configurable: true
  74849. });
  74850. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  74851. get: function () {
  74852. return this._supportsTangents;
  74853. },
  74854. enumerable: true,
  74855. configurable: true
  74856. });
  74857. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  74858. get: function () {
  74859. return this._targets.length;
  74860. },
  74861. enumerable: true,
  74862. configurable: true
  74863. });
  74864. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  74865. get: function () {
  74866. return this._activeTargets.length;
  74867. },
  74868. enumerable: true,
  74869. configurable: true
  74870. });
  74871. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  74872. get: function () {
  74873. return this._influences;
  74874. },
  74875. enumerable: true,
  74876. configurable: true
  74877. });
  74878. MorphTargetManager.prototype.getActiveTarget = function (index) {
  74879. return this._activeTargets.data[index];
  74880. };
  74881. MorphTargetManager.prototype.getTarget = function (index) {
  74882. return this._targets[index];
  74883. };
  74884. MorphTargetManager.prototype.addTarget = function (target) {
  74885. var _this = this;
  74886. this._targets.push(target);
  74887. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  74888. _this._syncActiveTargets(needUpdate);
  74889. }));
  74890. this._syncActiveTargets(true);
  74891. };
  74892. MorphTargetManager.prototype.removeTarget = function (target) {
  74893. var index = this._targets.indexOf(target);
  74894. if (index >= 0) {
  74895. this._targets.splice(index, 1);
  74896. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  74897. this._syncActiveTargets(true);
  74898. }
  74899. };
  74900. /**
  74901. * Serializes the current manager into a Serialization object.
  74902. * Returns the serialized object.
  74903. */
  74904. MorphTargetManager.prototype.serialize = function () {
  74905. var serializationObject = {};
  74906. serializationObject.id = this.uniqueId;
  74907. serializationObject.targets = [];
  74908. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74909. var target = _a[_i];
  74910. serializationObject.targets.push(target.serialize());
  74911. }
  74912. return serializationObject;
  74913. };
  74914. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  74915. var influenceCount = 0;
  74916. this._activeTargets.reset();
  74917. this._supportsNormals = true;
  74918. this._supportsTangents = true;
  74919. this._vertexCount = 0;
  74920. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74921. var target = _a[_i];
  74922. this._activeTargets.push(target);
  74923. this._tempInfluences[influenceCount++] = target.influence;
  74924. var positions = target.getPositions();
  74925. if (positions) {
  74926. this._supportsNormals = this._supportsNormals && target.hasNormals;
  74927. this._supportsTangents = this._supportsTangents && target.hasTangents;
  74928. var vertexCount = positions.length / 3;
  74929. if (this._vertexCount === 0) {
  74930. this._vertexCount = vertexCount;
  74931. }
  74932. else if (this._vertexCount !== vertexCount) {
  74933. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  74934. return;
  74935. }
  74936. }
  74937. }
  74938. if (!this._influences || this._influences.length !== influenceCount) {
  74939. this._influences = new Float32Array(influenceCount);
  74940. }
  74941. for (var index = 0; index < influenceCount; index++) {
  74942. this._influences[index] = this._tempInfluences[index];
  74943. }
  74944. if (needUpdate && this._scene) {
  74945. // Flag meshes as dirty to resync with the active targets
  74946. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  74947. var mesh = _c[_b];
  74948. if (mesh.morphTargetManager === this) {
  74949. mesh._syncGeometryWithMorphTargetManager();
  74950. }
  74951. }
  74952. }
  74953. };
  74954. // Statics
  74955. MorphTargetManager.Parse = function (serializationObject, scene) {
  74956. var result = new MorphTargetManager(scene);
  74957. result._uniqueId = serializationObject.id;
  74958. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  74959. var targetData = _a[_i];
  74960. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  74961. }
  74962. return result;
  74963. };
  74964. return MorphTargetManager;
  74965. }());
  74966. BABYLON.MorphTargetManager = MorphTargetManager;
  74967. })(BABYLON || (BABYLON = {}));
  74968. //# sourceMappingURL=babylon.morphTargetManager.js.map
  74969. var BABYLON;
  74970. (function (BABYLON) {
  74971. var Octree = /** @class */ (function () {
  74972. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  74973. if (maxDepth === void 0) { maxDepth = 2; }
  74974. this.maxDepth = maxDepth;
  74975. this.dynamicContent = new Array();
  74976. this._maxBlockCapacity = maxBlockCapacity || 64;
  74977. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  74978. this._creationFunc = creationFunc;
  74979. }
  74980. // Methods
  74981. Octree.prototype.update = function (worldMin, worldMax, entries) {
  74982. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  74983. };
  74984. Octree.prototype.addMesh = function (entry) {
  74985. for (var index = 0; index < this.blocks.length; index++) {
  74986. var block = this.blocks[index];
  74987. block.addEntry(entry);
  74988. }
  74989. };
  74990. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  74991. this._selectionContent.reset();
  74992. for (var index = 0; index < this.blocks.length; index++) {
  74993. var block = this.blocks[index];
  74994. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  74995. }
  74996. if (allowDuplicate) {
  74997. this._selectionContent.concat(this.dynamicContent);
  74998. }
  74999. else {
  75000. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75001. }
  75002. return this._selectionContent;
  75003. };
  75004. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  75005. this._selectionContent.reset();
  75006. for (var index = 0; index < this.blocks.length; index++) {
  75007. var block = this.blocks[index];
  75008. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  75009. }
  75010. if (allowDuplicate) {
  75011. this._selectionContent.concat(this.dynamicContent);
  75012. }
  75013. else {
  75014. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75015. }
  75016. return this._selectionContent;
  75017. };
  75018. Octree.prototype.intersectsRay = function (ray) {
  75019. this._selectionContent.reset();
  75020. for (var index = 0; index < this.blocks.length; index++) {
  75021. var block = this.blocks[index];
  75022. block.intersectsRay(ray, this._selectionContent);
  75023. }
  75024. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  75025. return this._selectionContent;
  75026. };
  75027. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  75028. target.blocks = new Array();
  75029. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  75030. // Segmenting space
  75031. for (var x = 0; x < 2; x++) {
  75032. for (var y = 0; y < 2; y++) {
  75033. for (var z = 0; z < 2; z++) {
  75034. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  75035. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  75036. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  75037. block.addEntries(entries);
  75038. target.blocks.push(block);
  75039. }
  75040. }
  75041. }
  75042. };
  75043. Octree.CreationFuncForMeshes = function (entry, block) {
  75044. var boundingInfo = entry.getBoundingInfo();
  75045. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75046. block.entries.push(entry);
  75047. }
  75048. };
  75049. Octree.CreationFuncForSubMeshes = function (entry, block) {
  75050. var boundingInfo = entry.getBoundingInfo();
  75051. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  75052. block.entries.push(entry);
  75053. }
  75054. };
  75055. return Octree;
  75056. }());
  75057. BABYLON.Octree = Octree;
  75058. })(BABYLON || (BABYLON = {}));
  75059. //# sourceMappingURL=babylon.octree.js.map
  75060. var BABYLON;
  75061. (function (BABYLON) {
  75062. var OctreeBlock = /** @class */ (function () {
  75063. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  75064. this.entries = new Array();
  75065. this._boundingVectors = new Array();
  75066. this._capacity = capacity;
  75067. this._depth = depth;
  75068. this._maxDepth = maxDepth;
  75069. this._creationFunc = creationFunc;
  75070. this._minPoint = minPoint;
  75071. this._maxPoint = maxPoint;
  75072. this._boundingVectors.push(minPoint.clone());
  75073. this._boundingVectors.push(maxPoint.clone());
  75074. this._boundingVectors.push(minPoint.clone());
  75075. this._boundingVectors[2].x = maxPoint.x;
  75076. this._boundingVectors.push(minPoint.clone());
  75077. this._boundingVectors[3].y = maxPoint.y;
  75078. this._boundingVectors.push(minPoint.clone());
  75079. this._boundingVectors[4].z = maxPoint.z;
  75080. this._boundingVectors.push(maxPoint.clone());
  75081. this._boundingVectors[5].z = minPoint.z;
  75082. this._boundingVectors.push(maxPoint.clone());
  75083. this._boundingVectors[6].x = minPoint.x;
  75084. this._boundingVectors.push(maxPoint.clone());
  75085. this._boundingVectors[7].y = minPoint.y;
  75086. }
  75087. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  75088. // Property
  75089. get: function () {
  75090. return this._capacity;
  75091. },
  75092. enumerable: true,
  75093. configurable: true
  75094. });
  75095. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  75096. get: function () {
  75097. return this._minPoint;
  75098. },
  75099. enumerable: true,
  75100. configurable: true
  75101. });
  75102. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  75103. get: function () {
  75104. return this._maxPoint;
  75105. },
  75106. enumerable: true,
  75107. configurable: true
  75108. });
  75109. // Methods
  75110. OctreeBlock.prototype.addEntry = function (entry) {
  75111. if (this.blocks) {
  75112. for (var index = 0; index < this.blocks.length; index++) {
  75113. var block = this.blocks[index];
  75114. block.addEntry(entry);
  75115. }
  75116. return;
  75117. }
  75118. this._creationFunc(entry, this);
  75119. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  75120. this.createInnerBlocks();
  75121. }
  75122. };
  75123. OctreeBlock.prototype.addEntries = function (entries) {
  75124. for (var index = 0; index < entries.length; index++) {
  75125. var mesh = entries[index];
  75126. this.addEntry(mesh);
  75127. }
  75128. };
  75129. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  75130. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  75131. if (this.blocks) {
  75132. for (var index = 0; index < this.blocks.length; index++) {
  75133. var block = this.blocks[index];
  75134. block.select(frustumPlanes, selection, allowDuplicate);
  75135. }
  75136. return;
  75137. }
  75138. if (allowDuplicate) {
  75139. selection.concat(this.entries);
  75140. }
  75141. else {
  75142. selection.concatWithNoDuplicate(this.entries);
  75143. }
  75144. }
  75145. };
  75146. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  75147. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  75148. if (this.blocks) {
  75149. for (var index = 0; index < this.blocks.length; index++) {
  75150. var block = this.blocks[index];
  75151. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  75152. }
  75153. return;
  75154. }
  75155. if (allowDuplicate) {
  75156. selection.concat(this.entries);
  75157. }
  75158. else {
  75159. selection.concatWithNoDuplicate(this.entries);
  75160. }
  75161. }
  75162. };
  75163. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  75164. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  75165. if (this.blocks) {
  75166. for (var index = 0; index < this.blocks.length; index++) {
  75167. var block = this.blocks[index];
  75168. block.intersectsRay(ray, selection);
  75169. }
  75170. return;
  75171. }
  75172. selection.concatWithNoDuplicate(this.entries);
  75173. }
  75174. };
  75175. OctreeBlock.prototype.createInnerBlocks = function () {
  75176. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  75177. };
  75178. return OctreeBlock;
  75179. }());
  75180. BABYLON.OctreeBlock = OctreeBlock;
  75181. })(BABYLON || (BABYLON = {}));
  75182. //# sourceMappingURL=babylon.octreeBlock.js.map
  75183. var BABYLON;
  75184. (function (BABYLON) {
  75185. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  75186. __extends(VRDistortionCorrectionPostProcess, _super);
  75187. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  75188. var _this = _super.call(this, name, "vrDistortionCorrection", [
  75189. 'LensCenter',
  75190. 'Scale',
  75191. 'ScaleIn',
  75192. 'HmdWarpParam'
  75193. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  75194. _this._isRightEye = isRightEye;
  75195. _this._distortionFactors = vrMetrics.distortionK;
  75196. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  75197. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  75198. _this.adaptScaleToCurrentViewport = true;
  75199. _this.onSizeChangedObservable.add(function () {
  75200. _this.aspectRatio = _this.width * .5 / _this.height;
  75201. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  75202. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  75203. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  75204. });
  75205. _this.onApplyObservable.add(function (effect) {
  75206. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  75207. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  75208. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  75209. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  75210. });
  75211. return _this;
  75212. }
  75213. return VRDistortionCorrectionPostProcess;
  75214. }(BABYLON.PostProcess));
  75215. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  75216. })(BABYLON || (BABYLON = {}));
  75217. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  75218. var BABYLON;
  75219. (function (BABYLON) {
  75220. var AnaglyphPostProcess = /** @class */ (function (_super) {
  75221. __extends(AnaglyphPostProcess, _super);
  75222. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  75223. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  75224. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75225. _this.onApplyObservable.add(function (effect) {
  75226. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  75227. });
  75228. return _this;
  75229. }
  75230. return AnaglyphPostProcess;
  75231. }(BABYLON.PostProcess));
  75232. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  75233. })(BABYLON || (BABYLON = {}));
  75234. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  75235. var BABYLON;
  75236. (function (BABYLON) {
  75237. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  75238. __extends(StereoscopicInterlacePostProcess, _super);
  75239. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  75240. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  75241. _this._passedProcess = rigCameras[0]._rigPostProcess;
  75242. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75243. _this.onSizeChangedObservable.add(function () {
  75244. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  75245. });
  75246. _this.onApplyObservable.add(function (effect) {
  75247. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  75248. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  75249. });
  75250. return _this;
  75251. }
  75252. return StereoscopicInterlacePostProcess;
  75253. }(BABYLON.PostProcess));
  75254. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  75255. })(BABYLON || (BABYLON = {}));
  75256. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  75257. var BABYLON;
  75258. (function (BABYLON) {
  75259. /**
  75260. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  75261. * Screen rotation is taken into account.
  75262. */
  75263. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  75264. function FreeCameraDeviceOrientationInput() {
  75265. var _this = this;
  75266. this._screenOrientationAngle = 0;
  75267. this._screenQuaternion = new BABYLON.Quaternion();
  75268. this._alpha = 0;
  75269. this._beta = 0;
  75270. this._gamma = 0;
  75271. this._orientationChanged = function () {
  75272. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  75273. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  75274. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  75275. };
  75276. this._deviceOrientation = function (evt) {
  75277. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  75278. _this._beta = evt.beta !== null ? evt.beta : 0;
  75279. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  75280. };
  75281. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  75282. this._orientationChanged();
  75283. }
  75284. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  75285. get: function () {
  75286. return this._camera;
  75287. },
  75288. set: function (camera) {
  75289. this._camera = camera;
  75290. if (this._camera != null && !this._camera.rotationQuaternion) {
  75291. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  75292. }
  75293. },
  75294. enumerable: true,
  75295. configurable: true
  75296. });
  75297. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75298. window.addEventListener("orientationchange", this._orientationChanged);
  75299. window.addEventListener("deviceorientation", this._deviceOrientation);
  75300. //In certain cases, the attach control is called AFTER orientation was changed,
  75301. //So this is needed.
  75302. this._orientationChanged();
  75303. };
  75304. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  75305. window.removeEventListener("orientationchange", this._orientationChanged);
  75306. window.removeEventListener("deviceorientation", this._deviceOrientation);
  75307. };
  75308. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  75309. //if no device orientation provided, don't update the rotation.
  75310. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  75311. if (!this._alpha)
  75312. return;
  75313. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  75314. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  75315. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  75316. //Mirror on XY Plane
  75317. this._camera.rotationQuaternion.z *= -1;
  75318. this._camera.rotationQuaternion.w *= -1;
  75319. };
  75320. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  75321. return "FreeCameraDeviceOrientationInput";
  75322. };
  75323. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  75324. return "deviceOrientation";
  75325. };
  75326. return FreeCameraDeviceOrientationInput;
  75327. }());
  75328. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  75329. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  75330. })(BABYLON || (BABYLON = {}));
  75331. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  75332. var BABYLON;
  75333. (function (BABYLON) {
  75334. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  75335. function ArcRotateCameraVRDeviceOrientationInput() {
  75336. this.alphaCorrection = 1;
  75337. this.betaCorrection = 1;
  75338. this.gammaCorrection = 1;
  75339. this._alpha = 0;
  75340. this._gamma = 0;
  75341. this._dirty = false;
  75342. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  75343. }
  75344. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  75345. this.camera.attachControl(element, noPreventDefault);
  75346. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  75347. };
  75348. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  75349. if (evt.alpha !== null) {
  75350. this._alpha = +evt.alpha | 0;
  75351. }
  75352. if (evt.gamma !== null) {
  75353. this._gamma = +evt.gamma | 0;
  75354. }
  75355. this._dirty = true;
  75356. };
  75357. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  75358. if (this._dirty) {
  75359. this._dirty = false;
  75360. if (this._gamma < 0) {
  75361. this._gamma = 180 + this._gamma;
  75362. }
  75363. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  75364. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  75365. }
  75366. };
  75367. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  75368. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  75369. };
  75370. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  75371. return "ArcRotateCameraVRDeviceOrientationInput";
  75372. };
  75373. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  75374. return "VRDeviceOrientation";
  75375. };
  75376. return ArcRotateCameraVRDeviceOrientationInput;
  75377. }());
  75378. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  75379. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  75380. })(BABYLON || (BABYLON = {}));
  75381. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  75382. var BABYLON;
  75383. (function (BABYLON) {
  75384. var VRCameraMetrics = /** @class */ (function () {
  75385. function VRCameraMetrics() {
  75386. this.compensateDistortion = true;
  75387. }
  75388. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  75389. get: function () {
  75390. return this.hResolution / (2 * this.vResolution);
  75391. },
  75392. enumerable: true,
  75393. configurable: true
  75394. });
  75395. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  75396. get: function () {
  75397. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  75398. },
  75399. enumerable: true,
  75400. configurable: true
  75401. });
  75402. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  75403. get: function () {
  75404. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75405. var h = (4 * meters) / this.hScreenSize;
  75406. return BABYLON.Matrix.Translation(h, 0, 0);
  75407. },
  75408. enumerable: true,
  75409. configurable: true
  75410. });
  75411. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  75412. get: function () {
  75413. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  75414. var h = (4 * meters) / this.hScreenSize;
  75415. return BABYLON.Matrix.Translation(-h, 0, 0);
  75416. },
  75417. enumerable: true,
  75418. configurable: true
  75419. });
  75420. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  75421. get: function () {
  75422. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  75423. },
  75424. enumerable: true,
  75425. configurable: true
  75426. });
  75427. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  75428. get: function () {
  75429. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  75430. },
  75431. enumerable: true,
  75432. configurable: true
  75433. });
  75434. VRCameraMetrics.GetDefault = function () {
  75435. var result = new VRCameraMetrics();
  75436. result.hResolution = 1280;
  75437. result.vResolution = 800;
  75438. result.hScreenSize = 0.149759993;
  75439. result.vScreenSize = 0.0935999975;
  75440. result.vScreenCenter = 0.0467999987;
  75441. result.eyeToScreenDistance = 0.0410000011;
  75442. result.lensSeparationDistance = 0.0635000020;
  75443. result.interpupillaryDistance = 0.0640000030;
  75444. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  75445. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  75446. result.postProcessScaleFactor = 1.714605507808412;
  75447. result.lensCenterOffset = 0.151976421;
  75448. return result;
  75449. };
  75450. return VRCameraMetrics;
  75451. }());
  75452. BABYLON.VRCameraMetrics = VRCameraMetrics;
  75453. })(BABYLON || (BABYLON = {}));
  75454. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  75455. var BABYLON;
  75456. (function (BABYLON) {
  75457. /**
  75458. * This represents a WebVR camera.
  75459. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  75460. * @example http://doc.babylonjs.com/how_to/webvr_camera
  75461. */
  75462. var WebVRFreeCamera = /** @class */ (function (_super) {
  75463. __extends(WebVRFreeCamera, _super);
  75464. /**
  75465. * Instantiates a WebVRFreeCamera.
  75466. * @param name The name of the WebVRFreeCamera
  75467. * @param position The starting anchor position for the camera
  75468. * @param scene The scene the camera belongs to
  75469. * @param webVROptions a set of customizable options for the webVRCamera
  75470. */
  75471. function WebVRFreeCamera(name, position, scene, webVROptions) {
  75472. if (webVROptions === void 0) { webVROptions = {}; }
  75473. var _this = _super.call(this, name, position, scene) || this;
  75474. _this.webVROptions = webVROptions;
  75475. /**
  75476. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  75477. */
  75478. _this._vrDevice = null;
  75479. /**
  75480. * The rawPose of the vrDevice.
  75481. */
  75482. _this.rawPose = null;
  75483. _this._specsVersion = "1.1";
  75484. _this._attached = false;
  75485. _this._descendants = [];
  75486. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75487. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75488. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  75489. _this._standingMatrix = null;
  75490. /**
  75491. * Represents device position in babylon space.
  75492. */
  75493. _this.devicePosition = BABYLON.Vector3.Zero();
  75494. /**
  75495. * Represents device rotation in babylon space.
  75496. */
  75497. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  75498. /**
  75499. * The scale of the device to be used when translating from device space to babylon space.
  75500. */
  75501. _this.deviceScaleFactor = 1;
  75502. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75503. _this._worldToDevice = BABYLON.Matrix.Identity();
  75504. /**
  75505. * References to the webVR controllers for the vrDevice.
  75506. */
  75507. _this.controllers = [];
  75508. /**
  75509. * Emits an event when a controller is attached.
  75510. */
  75511. _this.onControllersAttachedObservable = new BABYLON.Observable();
  75512. /**
  75513. * Emits an event when a controller's mesh has been loaded;
  75514. */
  75515. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75516. /**
  75517. * If the rig cameras be used as parent instead of this camera.
  75518. */
  75519. _this.rigParenting = true;
  75520. _this._defaultHeight = undefined;
  75521. _this._workingVector = BABYLON.Vector3.Zero();
  75522. _this._oneVector = BABYLON.Vector3.One();
  75523. _this._workingMatrix = BABYLON.Matrix.Identity();
  75524. _this._cache.position = BABYLON.Vector3.Zero();
  75525. if (webVROptions.defaultHeight) {
  75526. _this._defaultHeight = webVROptions.defaultHeight;
  75527. _this.position.y = _this._defaultHeight;
  75528. }
  75529. _this.minZ = 0.1;
  75530. //legacy support - the compensation boolean was removed.
  75531. if (arguments.length === 5) {
  75532. _this.webVROptions = arguments[4];
  75533. }
  75534. // default webVR options
  75535. if (_this.webVROptions.trackPosition == undefined) {
  75536. _this.webVROptions.trackPosition = true;
  75537. }
  75538. if (_this.webVROptions.controllerMeshes == undefined) {
  75539. _this.webVROptions.controllerMeshes = true;
  75540. }
  75541. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  75542. _this.webVROptions.defaultLightingOnControllers = true;
  75543. }
  75544. _this.rotationQuaternion = new BABYLON.Quaternion();
  75545. if (_this.webVROptions && _this.webVROptions.positionScale) {
  75546. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  75547. }
  75548. //enable VR
  75549. var engine = _this.getEngine();
  75550. _this._onVREnabled = function (success) { if (success) {
  75551. _this.initControllers();
  75552. } };
  75553. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  75554. engine.initWebVR().add(function (event) {
  75555. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  75556. return;
  75557. }
  75558. _this._vrDevice = event.vrDisplay;
  75559. //reset the rig parameters.
  75560. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  75561. if (_this._attached) {
  75562. _this.getEngine().enableVR();
  75563. }
  75564. });
  75565. if (typeof (VRFrameData) !== "undefined")
  75566. _this._frameData = new VRFrameData();
  75567. /**
  75568. * The idea behind the following lines:
  75569. * objects that have the camera as parent should actually have the rig cameras as a parent.
  75570. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  75571. * the second will not show it correctly.
  75572. *
  75573. * To solve this - each object that has the camera as parent will be added to a protected array.
  75574. * When the rig camera renders, it will take this array and set all of those to be its children.
  75575. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  75576. * Amazing!
  75577. */
  75578. scene.onBeforeCameraRenderObservable.add(function (camera) {
  75579. if (camera.parent === _this && _this.rigParenting) {
  75580. _this._descendants = _this.getDescendants(true, function (n) {
  75581. // don't take the cameras or the controllers!
  75582. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  75583. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  75584. return !isController && !isRigCamera;
  75585. });
  75586. _this._descendants.forEach(function (node) {
  75587. node.parent = camera;
  75588. });
  75589. }
  75590. });
  75591. scene.onAfterCameraRenderObservable.add(function (camera) {
  75592. if (camera.parent === _this && _this.rigParenting) {
  75593. _this._descendants.forEach(function (node) {
  75594. node.parent = _this;
  75595. });
  75596. }
  75597. });
  75598. return _this;
  75599. }
  75600. /**
  75601. * Gets the device distance from the ground.
  75602. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  75603. */
  75604. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  75605. if (this._standingMatrix && this._defaultHeight === undefined) {
  75606. // Add standing matrix offset to get real offset from ground in room
  75607. this._standingMatrix.getTranslationToRef(this._workingVector);
  75608. return this._deviceRoomPosition.y + this._workingVector.y;
  75609. }
  75610. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  75611. return this._defaultHeight || 0;
  75612. };
  75613. /**
  75614. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  75615. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  75616. */
  75617. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  75618. var _this = this;
  75619. if (callback === void 0) { callback = function (bool) { }; }
  75620. // Use standing matrix if available
  75621. if (!navigator || !navigator.getVRDisplays) {
  75622. callback(false);
  75623. }
  75624. else {
  75625. navigator.getVRDisplays().then(function (displays) {
  75626. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  75627. callback(false);
  75628. }
  75629. else {
  75630. _this._standingMatrix = new BABYLON.Matrix();
  75631. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  75632. if (!_this.getScene().useRightHandedSystem) {
  75633. [2, 6, 8, 9, 14].forEach(function (num) {
  75634. if (_this._standingMatrix) {
  75635. _this._standingMatrix.m[num] *= -1;
  75636. }
  75637. });
  75638. }
  75639. callback(true);
  75640. }
  75641. });
  75642. }
  75643. };
  75644. /**
  75645. * Disposes the camera
  75646. */
  75647. WebVRFreeCamera.prototype.dispose = function () {
  75648. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  75649. _super.prototype.dispose.call(this);
  75650. };
  75651. /**
  75652. * Gets a vrController by name.
  75653. * @param name The name of the controller to retreive
  75654. * @returns the controller matching the name specified or null if not found
  75655. */
  75656. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  75657. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  75658. var gp = _a[_i];
  75659. if (gp.hand === name) {
  75660. return gp;
  75661. }
  75662. }
  75663. return null;
  75664. };
  75665. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  75666. /**
  75667. * The controller corrisponding to the users left hand.
  75668. */
  75669. get: function () {
  75670. if (!this._leftController) {
  75671. this._leftController = this.getControllerByName("left");
  75672. }
  75673. return this._leftController;
  75674. },
  75675. enumerable: true,
  75676. configurable: true
  75677. });
  75678. ;
  75679. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  75680. /**
  75681. * The controller corrisponding to the users right hand.
  75682. */
  75683. get: function () {
  75684. if (!this._rightController) {
  75685. this._rightController = this.getControllerByName("right");
  75686. }
  75687. return this._rightController;
  75688. },
  75689. enumerable: true,
  75690. configurable: true
  75691. });
  75692. ;
  75693. /**
  75694. * Casts a ray forward from the vrCamera's gaze.
  75695. * @param length Length of the ray (default: 100)
  75696. * @returns the ray corrisponding to the gaze
  75697. */
  75698. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  75699. if (length === void 0) { length = 100; }
  75700. if (this.leftCamera) {
  75701. // Use left eye to avoid computation to compute center on every call
  75702. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  75703. }
  75704. else {
  75705. return _super.prototype.getForwardRay.call(this, length);
  75706. }
  75707. };
  75708. /**
  75709. * Updates the camera based on device's frame data
  75710. */
  75711. WebVRFreeCamera.prototype._checkInputs = function () {
  75712. if (this._vrDevice && this._vrDevice.isPresenting) {
  75713. this._vrDevice.getFrameData(this._frameData);
  75714. this.updateFromDevice(this._frameData.pose);
  75715. }
  75716. _super.prototype._checkInputs.call(this);
  75717. };
  75718. /**
  75719. * Updates the poseControlled values based on the input device pose.
  75720. * @param poseData Pose coming from the device
  75721. */
  75722. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  75723. if (poseData && poseData.orientation) {
  75724. this.rawPose = poseData;
  75725. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  75726. if (this.getScene().useRightHandedSystem) {
  75727. this._deviceRoomRotationQuaternion.z *= -1;
  75728. this._deviceRoomRotationQuaternion.w *= -1;
  75729. }
  75730. if (this.webVROptions.trackPosition && this.rawPose.position) {
  75731. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  75732. if (this.getScene().useRightHandedSystem) {
  75733. this._deviceRoomPosition.z *= -1;
  75734. }
  75735. }
  75736. }
  75737. };
  75738. /**
  75739. * WebVR's attach control will start broadcasting frames to the device.
  75740. * Note that in certain browsers (chrome for example) this function must be called
  75741. * within a user-interaction callback. Example:
  75742. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  75743. *
  75744. * @param element html element to attach the vrDevice to
  75745. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  75746. */
  75747. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  75748. _super.prototype.attachControl.call(this, element, noPreventDefault);
  75749. this._attached = true;
  75750. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  75751. if (this._vrDevice) {
  75752. this.getEngine().enableVR();
  75753. }
  75754. };
  75755. /**
  75756. * Detaches the camera from the html element and disables VR
  75757. *
  75758. * @param element html element to detach from
  75759. */
  75760. WebVRFreeCamera.prototype.detachControl = function (element) {
  75761. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  75762. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  75763. _super.prototype.detachControl.call(this, element);
  75764. this._attached = false;
  75765. this.getEngine().disableVR();
  75766. };
  75767. /**
  75768. * @returns the name of this class
  75769. */
  75770. WebVRFreeCamera.prototype.getClassName = function () {
  75771. return "WebVRFreeCamera";
  75772. };
  75773. /**
  75774. * Calls resetPose on the vrDisplay
  75775. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  75776. */
  75777. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  75778. //uses the vrDisplay's "resetPose()".
  75779. //pitch and roll won't be affected.
  75780. this._vrDevice.resetPose();
  75781. };
  75782. /**
  75783. * Updates the rig cameras (left and right eye)
  75784. */
  75785. WebVRFreeCamera.prototype._updateRigCameras = function () {
  75786. var camLeft = this._rigCameras[0];
  75787. var camRight = this._rigCameras[1];
  75788. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  75789. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  75790. camLeft.position.copyFrom(this._deviceRoomPosition);
  75791. camRight.position.copyFrom(this._deviceRoomPosition);
  75792. };
  75793. /**
  75794. * Updates the cached values of the camera
  75795. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  75796. */
  75797. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  75798. var _this = this;
  75799. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  75800. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  75801. if (!this.updateCacheCalled) {
  75802. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  75803. this.updateCacheCalled = true;
  75804. this.update();
  75805. }
  75806. // Set working vector to the device position in room space rotated by the new rotation
  75807. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  75808. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  75809. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  75810. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  75811. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  75812. // Add translation from anchor position
  75813. this._deviceToWorld.getTranslationToRef(this._workingVector);
  75814. this._workingVector.addInPlace(this.position);
  75815. this._workingVector.subtractInPlace(this._cache.position);
  75816. this._deviceToWorld.setTranslation(this._workingVector);
  75817. // Set an inverted matrix to be used when updating the camera
  75818. this._deviceToWorld.invertToRef(this._worldToDevice);
  75819. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  75820. this.controllers.forEach(function (controller) {
  75821. controller._deviceToWorld = _this._deviceToWorld;
  75822. controller.update();
  75823. });
  75824. }
  75825. if (!ignoreParentClass) {
  75826. _super.prototype._updateCache.call(this);
  75827. }
  75828. this.updateCacheCalled = false;
  75829. };
  75830. /**
  75831. * Updates the current device position and rotation in the babylon world
  75832. */
  75833. WebVRFreeCamera.prototype.update = function () {
  75834. // Get current device position in babylon world
  75835. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  75836. // Get current device rotation in babylon world
  75837. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  75838. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  75839. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75840. _super.prototype.update.call(this);
  75841. };
  75842. /**
  75843. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  75844. * @returns an identity matrix
  75845. */
  75846. WebVRFreeCamera.prototype._getViewMatrix = function () {
  75847. return BABYLON.Matrix.Identity();
  75848. };
  75849. /**
  75850. * This function is called by the two RIG cameras.
  75851. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  75852. */
  75853. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  75854. var _this = this;
  75855. //WebVR 1.1
  75856. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  75857. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  75858. if (!this.getScene().useRightHandedSystem) {
  75859. [2, 6, 8, 9, 14].forEach(function (num) {
  75860. _this._webvrViewMatrix.m[num] *= -1;
  75861. });
  75862. }
  75863. // update the camera rotation matrix
  75864. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  75865. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  75866. // Computing target and final matrix
  75867. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  75868. var parentCamera = this._cameraRigParams["parentCamera"];
  75869. // should the view matrix be updated with scale and position offset?
  75870. if (parentCamera.deviceScaleFactor !== 1) {
  75871. this._webvrViewMatrix.invert();
  75872. // scale the position, if set
  75873. if (parentCamera.deviceScaleFactor) {
  75874. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  75875. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  75876. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  75877. }
  75878. this._webvrViewMatrix.invert();
  75879. }
  75880. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  75881. return this._webvrViewMatrix;
  75882. };
  75883. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  75884. var _this = this;
  75885. var parentCamera = this.parent;
  75886. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  75887. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  75888. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  75889. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  75890. //babylon compatible matrix
  75891. if (!this.getScene().useRightHandedSystem) {
  75892. [8, 9, 10, 11].forEach(function (num) {
  75893. _this._projectionMatrix.m[num] *= -1;
  75894. });
  75895. }
  75896. return this._projectionMatrix;
  75897. };
  75898. /**
  75899. * Initializes the controllers and their meshes
  75900. */
  75901. WebVRFreeCamera.prototype.initControllers = function () {
  75902. var _this = this;
  75903. this.controllers = [];
  75904. var manager = this.getScene().gamepadManager;
  75905. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75906. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75907. var webVrController = gamepad;
  75908. if (webVrController.defaultModel) {
  75909. webVrController.defaultModel.setEnabled(false);
  75910. }
  75911. if (webVrController.hand === "right") {
  75912. _this._rightController = null;
  75913. }
  75914. if (webVrController.hand === "left") {
  75915. _this._rightController = null;
  75916. }
  75917. var controllerIndex = _this.controllers.indexOf(webVrController);
  75918. if (controllerIndex !== -1) {
  75919. _this.controllers.splice(controllerIndex, 1);
  75920. }
  75921. }
  75922. });
  75923. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75924. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75925. var webVrController_1 = gamepad;
  75926. webVrController_1._deviceToWorld = _this._deviceToWorld;
  75927. if (_this.webVROptions.controllerMeshes) {
  75928. if (webVrController_1.defaultModel) {
  75929. webVrController_1.defaultModel.setEnabled(true);
  75930. }
  75931. else {
  75932. // Load the meshes
  75933. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  75934. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  75935. if (_this.webVROptions.defaultLightingOnControllers) {
  75936. if (!_this._lightOnControllers) {
  75937. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  75938. }
  75939. var activateLightOnSubMeshes_1 = function (mesh, light) {
  75940. var children = mesh.getChildren();
  75941. if (children.length !== 0) {
  75942. children.forEach(function (mesh) {
  75943. light.includedOnlyMeshes.push(mesh);
  75944. activateLightOnSubMeshes_1(mesh, light);
  75945. });
  75946. }
  75947. };
  75948. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  75949. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  75950. }
  75951. });
  75952. }
  75953. }
  75954. webVrController_1.attachToPoseControlledCamera(_this);
  75955. // since this is async - sanity check. Is the controller already stored?
  75956. if (_this.controllers.indexOf(webVrController_1) === -1) {
  75957. //add to the controllers array
  75958. _this.controllers.push(webVrController_1);
  75959. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  75960. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  75961. // So we're overriding setting left & right manually to be sure
  75962. var firstViveWandDetected = false;
  75963. for (var i = 0; i < _this.controllers.length; i++) {
  75964. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75965. if (!firstViveWandDetected) {
  75966. firstViveWandDetected = true;
  75967. _this.controllers[i].hand = "left";
  75968. }
  75969. else {
  75970. _this.controllers[i].hand = "right";
  75971. }
  75972. }
  75973. }
  75974. //did we find enough controllers? Great! let the developer know.
  75975. if (_this.controllers.length >= 2) {
  75976. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  75977. }
  75978. }
  75979. }
  75980. });
  75981. };
  75982. return WebVRFreeCamera;
  75983. }(BABYLON.FreeCamera));
  75984. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  75985. })(BABYLON || (BABYLON = {}));
  75986. //# sourceMappingURL=babylon.webVRCamera.js.map
  75987. var BABYLON;
  75988. (function (BABYLON) {
  75989. // We're mainly based on the logic defined into the FreeCamera code
  75990. /**
  75991. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  75992. * being tilted forward or back and left or right.
  75993. */
  75994. var DeviceOrientationCamera = /** @class */ (function (_super) {
  75995. __extends(DeviceOrientationCamera, _super);
  75996. /**
  75997. * Creates a new device orientation camera. @see DeviceOrientationCamera
  75998. * @param name The name of the camera
  75999. * @param position The start position camera
  76000. * @param scene The scene the camera belongs to
  76001. */
  76002. function DeviceOrientationCamera(name, position, scene) {
  76003. var _this = _super.call(this, name, position, scene) || this;
  76004. _this._quaternionCache = new BABYLON.Quaternion();
  76005. _this.inputs.addDeviceOrientation();
  76006. return _this;
  76007. }
  76008. /**
  76009. * Gets the current instance class name ("DeviceOrientationCamera").
  76010. * This helps avoiding instanceof at run time.
  76011. * @returns the class name
  76012. */
  76013. DeviceOrientationCamera.prototype.getClassName = function () {
  76014. return "DeviceOrientationCamera";
  76015. };
  76016. /**
  76017. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  76018. */
  76019. DeviceOrientationCamera.prototype._checkInputs = function () {
  76020. _super.prototype._checkInputs.call(this);
  76021. this._quaternionCache.copyFrom(this.rotationQuaternion);
  76022. if (this._initialQuaternion) {
  76023. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76024. }
  76025. };
  76026. /**
  76027. * Reset the camera to its default orientation on the specified axis only.
  76028. * @param axis The axis to reset
  76029. */
  76030. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  76031. var _this = this;
  76032. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  76033. //can only work if this camera has a rotation quaternion already.
  76034. if (!this.rotationQuaternion)
  76035. return;
  76036. if (!this._initialQuaternion) {
  76037. this._initialQuaternion = new BABYLON.Quaternion();
  76038. }
  76039. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  76040. ['x', 'y', 'z'].forEach(function (axisName) {
  76041. if (!axis[axisName]) {
  76042. _this._initialQuaternion[axisName] = 0;
  76043. }
  76044. else {
  76045. _this._initialQuaternion[axisName] *= -1;
  76046. }
  76047. });
  76048. this._initialQuaternion.normalize();
  76049. //force rotation update
  76050. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  76051. };
  76052. return DeviceOrientationCamera;
  76053. }(BABYLON.FreeCamera));
  76054. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  76055. })(BABYLON || (BABYLON = {}));
  76056. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  76057. var BABYLON;
  76058. (function (BABYLON) {
  76059. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  76060. __extends(VRDeviceOrientationFreeCamera, _super);
  76061. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76062. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76063. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76064. var _this = _super.call(this, name, position, scene) || this;
  76065. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76066. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76067. return _this;
  76068. }
  76069. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  76070. return "VRDeviceOrientationFreeCamera";
  76071. };
  76072. return VRDeviceOrientationFreeCamera;
  76073. }(BABYLON.DeviceOrientationCamera));
  76074. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  76075. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  76076. __extends(VRDeviceOrientationGamepadCamera, _super);
  76077. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  76078. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76079. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76080. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  76081. _this.inputs.addGamepad();
  76082. return _this;
  76083. }
  76084. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  76085. return "VRDeviceOrientationGamepadCamera";
  76086. };
  76087. return VRDeviceOrientationGamepadCamera;
  76088. }(VRDeviceOrientationFreeCamera));
  76089. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  76090. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  76091. __extends(VRDeviceOrientationArcRotateCamera, _super);
  76092. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  76093. if (compensateDistortion === void 0) { compensateDistortion = true; }
  76094. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  76095. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76096. vrCameraMetrics.compensateDistortion = compensateDistortion;
  76097. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  76098. _this.inputs.addVRDeviceOrientation();
  76099. return _this;
  76100. }
  76101. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  76102. return "VRDeviceOrientationArcRotateCamera";
  76103. };
  76104. return VRDeviceOrientationArcRotateCamera;
  76105. }(BABYLON.ArcRotateCamera));
  76106. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  76107. })(BABYLON || (BABYLON = {}));
  76108. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  76109. var BABYLON;
  76110. (function (BABYLON) {
  76111. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  76112. __extends(AnaglyphFreeCamera, _super);
  76113. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  76114. var _this = _super.call(this, name, position, scene) || this;
  76115. _this.interaxialDistance = interaxialDistance;
  76116. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76117. return _this;
  76118. }
  76119. AnaglyphFreeCamera.prototype.getClassName = function () {
  76120. return "AnaglyphFreeCamera";
  76121. };
  76122. return AnaglyphFreeCamera;
  76123. }(BABYLON.FreeCamera));
  76124. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  76125. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  76126. __extends(AnaglyphArcRotateCamera, _super);
  76127. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  76128. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76129. _this.interaxialDistance = interaxialDistance;
  76130. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76131. return _this;
  76132. }
  76133. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  76134. return "AnaglyphArcRotateCamera";
  76135. };
  76136. return AnaglyphArcRotateCamera;
  76137. }(BABYLON.ArcRotateCamera));
  76138. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  76139. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  76140. __extends(AnaglyphGamepadCamera, _super);
  76141. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  76142. var _this = _super.call(this, name, position, scene) || this;
  76143. _this.interaxialDistance = interaxialDistance;
  76144. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76145. return _this;
  76146. }
  76147. AnaglyphGamepadCamera.prototype.getClassName = function () {
  76148. return "AnaglyphGamepadCamera";
  76149. };
  76150. return AnaglyphGamepadCamera;
  76151. }(BABYLON.GamepadCamera));
  76152. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  76153. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  76154. __extends(AnaglyphUniversalCamera, _super);
  76155. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  76156. var _this = _super.call(this, name, position, scene) || this;
  76157. _this.interaxialDistance = interaxialDistance;
  76158. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  76159. return _this;
  76160. }
  76161. AnaglyphUniversalCamera.prototype.getClassName = function () {
  76162. return "AnaglyphUniversalCamera";
  76163. };
  76164. return AnaglyphUniversalCamera;
  76165. }(BABYLON.UniversalCamera));
  76166. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  76167. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  76168. __extends(StereoscopicFreeCamera, _super);
  76169. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76170. var _this = _super.call(this, name, position, scene) || this;
  76171. _this.interaxialDistance = interaxialDistance;
  76172. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76173. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76174. return _this;
  76175. }
  76176. StereoscopicFreeCamera.prototype.getClassName = function () {
  76177. return "StereoscopicFreeCamera";
  76178. };
  76179. return StereoscopicFreeCamera;
  76180. }(BABYLON.FreeCamera));
  76181. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  76182. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  76183. __extends(StereoscopicArcRotateCamera, _super);
  76184. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  76185. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  76186. _this.interaxialDistance = interaxialDistance;
  76187. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76188. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76189. return _this;
  76190. }
  76191. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  76192. return "StereoscopicArcRotateCamera";
  76193. };
  76194. return StereoscopicArcRotateCamera;
  76195. }(BABYLON.ArcRotateCamera));
  76196. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  76197. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  76198. __extends(StereoscopicGamepadCamera, _super);
  76199. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76200. var _this = _super.call(this, name, position, scene) || this;
  76201. _this.interaxialDistance = interaxialDistance;
  76202. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76203. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76204. return _this;
  76205. }
  76206. StereoscopicGamepadCamera.prototype.getClassName = function () {
  76207. return "StereoscopicGamepadCamera";
  76208. };
  76209. return StereoscopicGamepadCamera;
  76210. }(BABYLON.GamepadCamera));
  76211. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  76212. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  76213. __extends(StereoscopicUniversalCamera, _super);
  76214. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  76215. var _this = _super.call(this, name, position, scene) || this;
  76216. _this.interaxialDistance = interaxialDistance;
  76217. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  76218. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  76219. return _this;
  76220. }
  76221. StereoscopicUniversalCamera.prototype.getClassName = function () {
  76222. return "StereoscopicUniversalCamera";
  76223. };
  76224. return StereoscopicUniversalCamera;
  76225. }(BABYLON.UniversalCamera));
  76226. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  76227. })(BABYLON || (BABYLON = {}));
  76228. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  76229. var BABYLON;
  76230. (function (BABYLON) {
  76231. /**
  76232. * Helps to quickly add VR support to an existing scene.
  76233. * See http://doc.babylonjs.com/how_to/webvr_helper
  76234. */
  76235. var VRExperienceHelper = /** @class */ (function () {
  76236. /**
  76237. * Instantiates a VRExperienceHelper.
  76238. * Helps to quickly add VR support to an existing scene.
  76239. * @param scene The scene the VRExperienceHelper belongs to.
  76240. * @param webVROptions Options to modify the vr experience helper's behavior.
  76241. */
  76242. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  76243. if (webVROptions === void 0) { webVROptions = {}; }
  76244. var _this = this;
  76245. this.webVROptions = webVROptions;
  76246. // Can the system support WebVR, even if a headset isn't plugged in?
  76247. this._webVRsupported = false;
  76248. // If WebVR is supported, is a headset plugged in and are we ready to present?
  76249. this._webVRready = false;
  76250. // Are we waiting for the requestPresent callback to complete?
  76251. this._webVRrequesting = false;
  76252. // Are we presenting to the headset right now?
  76253. this._webVRpresenting = false;
  76254. // Are we presenting in the fullscreen fallback?
  76255. this._fullscreenVRpresenting = false;
  76256. /**
  76257. * Observable raised when entering VR.
  76258. */
  76259. this.onEnteringVRObservable = new BABYLON.Observable();
  76260. /**
  76261. * Observable raised when exiting VR.
  76262. */
  76263. this.onExitingVRObservable = new BABYLON.Observable();
  76264. /**
  76265. * Observable raised when controller mesh is loaded.
  76266. */
  76267. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  76268. this._useCustomVRButton = false;
  76269. this._teleportationRequested = false;
  76270. this._teleportationEnabledOnLeftController = false;
  76271. this._teleportationEnabledOnRightController = false;
  76272. this._interactionsEnabledOnLeftController = false;
  76273. this._interactionsEnabledOnRightController = false;
  76274. this._leftControllerReady = false;
  76275. this._rightControllerReady = false;
  76276. this._floorMeshesCollection = [];
  76277. this._teleportationAllowed = false;
  76278. this._rotationAllowed = true;
  76279. this._teleportationRequestInitiated = false;
  76280. this._teleportationBackRequestInitiated = false;
  76281. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  76282. this._rotationRightAsked = false;
  76283. this._rotationLeftAsked = false;
  76284. this._isDefaultTeleportationTarget = true;
  76285. this._teleportationFillColor = "#444444";
  76286. this._teleportationBorderColor = "#FFFFFF";
  76287. this._rotationAngle = 0;
  76288. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  76289. this._padSensibilityUp = 0.65;
  76290. this._padSensibilityDown = 0.35;
  76291. /**
  76292. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  76293. */
  76294. this.onNewMeshSelected = new BABYLON.Observable();
  76295. /**
  76296. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  76297. */
  76298. this.onNewMeshPicked = new BABYLON.Observable();
  76299. /**
  76300. * Observable raised before camera teleportation
  76301. */
  76302. this.onBeforeCameraTeleport = new BABYLON.Observable();
  76303. /**
  76304. * Observable raised after camera teleportation
  76305. */
  76306. this.onAfterCameraTeleport = new BABYLON.Observable();
  76307. /**
  76308. * Observable raised when current selected mesh gets unselected
  76309. */
  76310. this.onSelectedMeshUnselected = new BABYLON.Observable();
  76311. /**
  76312. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  76313. */
  76314. this.teleportationEnabled = true;
  76315. this._pointerDownOnMeshAsked = false;
  76316. this._isActionableMesh = false;
  76317. this._teleportationInitialized = false;
  76318. this._interactionsEnabled = false;
  76319. this._interactionsRequested = false;
  76320. this._displayGaze = true;
  76321. this._displayLaserPointer = true;
  76322. this._dpadPressed = true;
  76323. this._onResize = function () {
  76324. _this.moveButtonToBottomRight();
  76325. if (_this._fullscreenVRpresenting && _this._webVRready) {
  76326. _this.exitVR();
  76327. }
  76328. };
  76329. this._onFullscreenChange = function () {
  76330. if (document.fullscreen !== undefined) {
  76331. _this._fullscreenVRpresenting = document.fullscreen;
  76332. }
  76333. else if (document.mozFullScreen !== undefined) {
  76334. _this._fullscreenVRpresenting = document.mozFullScreen;
  76335. }
  76336. else if (document.webkitIsFullScreen !== undefined) {
  76337. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  76338. }
  76339. else if (document.msIsFullScreen !== undefined) {
  76340. _this._fullscreenVRpresenting = document.msIsFullScreen;
  76341. }
  76342. if (!_this._fullscreenVRpresenting && _this._canvas) {
  76343. _this.exitVR();
  76344. if (!_this._useCustomVRButton) {
  76345. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  76346. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  76347. }
  76348. }
  76349. };
  76350. this.beforeRender = function () {
  76351. _this._castRayAndSelectObject();
  76352. };
  76353. this._onNewGamepadConnected = function (gamepad) {
  76354. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76355. if (gamepad.leftStick) {
  76356. gamepad.onleftstickchanged(function (stickValues) {
  76357. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  76358. // Listening to classic/xbox gamepad only if no VR controller is active
  76359. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  76360. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  76361. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  76362. _this._checkTeleportWithRay(stickValues);
  76363. _this._checkTeleportBackwards(stickValues);
  76364. }
  76365. }
  76366. });
  76367. }
  76368. if (gamepad.rightStick) {
  76369. gamepad.onrightstickchanged(function (stickValues) {
  76370. if (_this._teleportationInitialized) {
  76371. _this._checkRotate(stickValues);
  76372. }
  76373. });
  76374. }
  76375. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  76376. gamepad.onbuttondown(function (buttonPressed) {
  76377. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76378. _this._selectionPointerDown();
  76379. }
  76380. });
  76381. gamepad.onbuttonup(function (buttonPressed) {
  76382. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  76383. _this._selectionPointerUp();
  76384. }
  76385. });
  76386. }
  76387. }
  76388. else {
  76389. var webVRController = gamepad;
  76390. _this._tryEnableInteractionOnController(webVRController);
  76391. }
  76392. };
  76393. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  76394. this._tryEnableInteractionOnController = function (webVRController) {
  76395. if (webVRController.hand === "left") {
  76396. _this._leftControllerReady = true;
  76397. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  76398. _this._enableInteractionOnController(webVRController);
  76399. }
  76400. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  76401. _this._enableTeleportationOnController(webVRController);
  76402. }
  76403. }
  76404. if (webVRController.hand === "right") {
  76405. _this._rightControllerReady = true;
  76406. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  76407. _this._enableInteractionOnController(webVRController);
  76408. }
  76409. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  76410. _this._enableTeleportationOnController(webVRController);
  76411. }
  76412. }
  76413. };
  76414. this._onNewGamepadDisconnected = function (gamepad) {
  76415. if (gamepad instanceof BABYLON.WebVRController) {
  76416. if (gamepad.hand === "left") {
  76417. _this._interactionsEnabledOnLeftController = false;
  76418. _this._teleportationEnabledOnLeftController = false;
  76419. _this._leftControllerReady = false;
  76420. if (_this._leftLaserPointer) {
  76421. _this._leftLaserPointer.dispose();
  76422. }
  76423. }
  76424. if (gamepad.hand === "right") {
  76425. _this._interactionsEnabledOnRightController = false;
  76426. _this._teleportationEnabledOnRightController = false;
  76427. _this._rightControllerReady = false;
  76428. if (_this._rightLaserPointer) {
  76429. _this._rightLaserPointer.dispose();
  76430. }
  76431. }
  76432. }
  76433. };
  76434. this._workingVector = BABYLON.Vector3.Zero();
  76435. this._workingQuaternion = BABYLON.Quaternion.Identity();
  76436. this._workingMatrix = BABYLON.Matrix.Identity();
  76437. this._scene = scene;
  76438. this._canvas = scene.getEngine().getRenderingCanvas();
  76439. // Parse options
  76440. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  76441. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  76442. }
  76443. if (webVROptions.createDeviceOrientationCamera === undefined) {
  76444. webVROptions.createDeviceOrientationCamera = true;
  76445. }
  76446. if (webVROptions.defaultHeight === undefined) {
  76447. webVROptions.defaultHeight = 1.7;
  76448. }
  76449. if (webVROptions.useCustomVRButton) {
  76450. this._useCustomVRButton = true;
  76451. if (webVROptions.customVRButton) {
  76452. this._btnVR = webVROptions.customVRButton;
  76453. }
  76454. }
  76455. if (webVROptions.rayLength) {
  76456. this._rayLength = webVROptions.rayLength;
  76457. }
  76458. this._defaultHeight = webVROptions.defaultHeight;
  76459. // Set position
  76460. if (this._scene.activeCamera) {
  76461. this._position = this._scene.activeCamera.position.clone();
  76462. }
  76463. else {
  76464. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  76465. }
  76466. // Set non-vr camera
  76467. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  76468. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  76469. // Copy data from existing camera
  76470. if (this._scene.activeCamera) {
  76471. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  76472. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  76473. // Set rotation from previous camera
  76474. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  76475. var targetCamera = this._scene.activeCamera;
  76476. if (targetCamera.rotationQuaternion) {
  76477. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  76478. }
  76479. else {
  76480. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  76481. }
  76482. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  76483. }
  76484. }
  76485. this._scene.activeCamera = this._deviceOrientationCamera;
  76486. if (this._canvas) {
  76487. this._scene.activeCamera.attachControl(this._canvas);
  76488. }
  76489. }
  76490. else {
  76491. this._existingCamera = this._scene.activeCamera;
  76492. }
  76493. // Create VR cameras
  76494. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76495. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  76496. }
  76497. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  76498. this._webVRCamera.useStandingMatrix();
  76499. // Create default button
  76500. if (!this._useCustomVRButton) {
  76501. this._btnVR = document.createElement("BUTTON");
  76502. this._btnVR.className = "babylonVRicon";
  76503. this._btnVR.id = "babylonVRiconbtn";
  76504. this._btnVR.title = "Click to switch to VR";
  76505. 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) }";
  76506. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  76507. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  76508. // css += ".babylonVRicon.vrdisplaysupported { }";
  76509. // css += ".babylonVRicon.vrdisplayready { }";
  76510. // css += ".babylonVRicon.vrdisplayrequesting { }";
  76511. var style = document.createElement('style');
  76512. style.appendChild(document.createTextNode(css));
  76513. document.getElementsByTagName('head')[0].appendChild(style);
  76514. this.moveButtonToBottomRight();
  76515. }
  76516. // VR button click event
  76517. if (this._btnVR) {
  76518. this._btnVR.addEventListener("click", function () {
  76519. if (!_this.isInVRMode) {
  76520. _this.enterVR();
  76521. }
  76522. else {
  76523. _this.exitVR();
  76524. }
  76525. });
  76526. }
  76527. // Window events
  76528. window.addEventListener("resize", this._onResize);
  76529. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  76530. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  76531. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  76532. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  76533. // Display vr button when headset is connected
  76534. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  76535. this.displayVRButton();
  76536. }
  76537. else {
  76538. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  76539. if (e.vrDisplay) {
  76540. _this.displayVRButton();
  76541. }
  76542. });
  76543. }
  76544. // Exiting VR mode using 'ESC' key on desktop
  76545. this._onKeyDown = function (event) {
  76546. if (event.keyCode === 27 && _this.isInVRMode) {
  76547. _this.exitVR();
  76548. }
  76549. };
  76550. document.addEventListener("keydown", this._onKeyDown);
  76551. // Exiting VR mode double tapping the touch screen
  76552. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  76553. if (_this.isInVRMode) {
  76554. _this.exitVR();
  76555. if (_this._fullscreenVRpresenting) {
  76556. _this._scene.getEngine().switchFullscreen(true);
  76557. }
  76558. }
  76559. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  76560. // Listen for WebVR display changes
  76561. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  76562. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  76563. this._onVRRequestPresentStart = function () {
  76564. _this._webVRrequesting = true;
  76565. _this.updateButtonVisibility();
  76566. };
  76567. this._onVRRequestPresentComplete = function (success) {
  76568. _this._webVRrequesting = false;
  76569. _this.updateButtonVisibility();
  76570. };
  76571. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  76572. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  76573. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  76574. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76575. scene.onDisposeObservable.add(function () {
  76576. _this.dispose();
  76577. });
  76578. // Gamepad connection events
  76579. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  76580. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  76581. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  76582. this.updateButtonVisibility();
  76583. //create easing functions
  76584. this._circleEase = new BABYLON.CircleEase();
  76585. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76586. }
  76587. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  76588. /** Return this.onEnteringVRObservable
  76589. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  76590. */
  76591. get: function () {
  76592. return this.onEnteringVRObservable;
  76593. },
  76594. enumerable: true,
  76595. configurable: true
  76596. });
  76597. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  76598. /** Return this.onExitingVRObservable
  76599. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  76600. */
  76601. get: function () {
  76602. return this.onExitingVRObservable;
  76603. },
  76604. enumerable: true,
  76605. configurable: true
  76606. });
  76607. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  76608. /** Return this.onControllerMeshLoadedObservable
  76609. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  76610. */
  76611. get: function () {
  76612. return this.onControllerMeshLoadedObservable;
  76613. },
  76614. enumerable: true,
  76615. configurable: true
  76616. });
  76617. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  76618. /**
  76619. * The mesh used to display where the user is going to teleport.
  76620. */
  76621. get: function () {
  76622. return this._teleportationTarget;
  76623. },
  76624. /**
  76625. * Sets the mesh to be used to display where the user is going to teleport.
  76626. */
  76627. set: function (value) {
  76628. if (value) {
  76629. value.name = "teleportationTarget";
  76630. this._isDefaultTeleportationTarget = false;
  76631. this._teleportationTarget = value;
  76632. }
  76633. },
  76634. enumerable: true,
  76635. configurable: true
  76636. });
  76637. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  76638. /**
  76639. * If the ray of the gaze should be displayed.
  76640. */
  76641. get: function () {
  76642. return this._displayGaze;
  76643. },
  76644. /**
  76645. * Sets if the ray of the gaze should be displayed.
  76646. */
  76647. set: function (value) {
  76648. this._displayGaze = value;
  76649. if (!value) {
  76650. this._gazeTracker.isVisible = false;
  76651. }
  76652. },
  76653. enumerable: true,
  76654. configurable: true
  76655. });
  76656. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  76657. /**
  76658. * If the ray of the LaserPointer should be displayed.
  76659. */
  76660. get: function () {
  76661. return this._displayLaserPointer;
  76662. },
  76663. /**
  76664. * Sets if the ray of the LaserPointer should be displayed.
  76665. */
  76666. set: function (value) {
  76667. this._displayLaserPointer = value;
  76668. if (!value) {
  76669. if (this._rightLaserPointer) {
  76670. this._rightLaserPointer.isVisible = false;
  76671. }
  76672. if (this._leftLaserPointer) {
  76673. this._leftLaserPointer.isVisible = false;
  76674. }
  76675. }
  76676. else {
  76677. if (this._rightLaserPointer) {
  76678. this._rightLaserPointer.isVisible = true;
  76679. }
  76680. else if (this._leftLaserPointer) {
  76681. this._leftLaserPointer.isVisible = true;
  76682. }
  76683. }
  76684. },
  76685. enumerable: true,
  76686. configurable: true
  76687. });
  76688. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  76689. /**
  76690. * The deviceOrientationCamera used as the camera when not in VR.
  76691. */
  76692. get: function () {
  76693. return this._deviceOrientationCamera;
  76694. },
  76695. enumerable: true,
  76696. configurable: true
  76697. });
  76698. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  76699. /**
  76700. * Based on the current WebVR support, returns the current VR camera used.
  76701. */
  76702. get: function () {
  76703. if (this._webVRready) {
  76704. return this._webVRCamera;
  76705. }
  76706. else {
  76707. return this._scene.activeCamera;
  76708. }
  76709. },
  76710. enumerable: true,
  76711. configurable: true
  76712. });
  76713. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  76714. /**
  76715. * The webVRCamera which is used when in VR.
  76716. */
  76717. get: function () {
  76718. return this._webVRCamera;
  76719. },
  76720. enumerable: true,
  76721. configurable: true
  76722. });
  76723. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  76724. /**
  76725. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  76726. */
  76727. get: function () {
  76728. return this._vrDeviceOrientationCamera;
  76729. },
  76730. enumerable: true,
  76731. configurable: true
  76732. });
  76733. // Raised when one of the controller has loaded successfully its associated default mesh
  76734. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  76735. this._tryEnableInteractionOnController(webVRController);
  76736. try {
  76737. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  76738. }
  76739. catch (err) {
  76740. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  76741. }
  76742. };
  76743. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  76744. /**
  76745. * Gets a value indicating if we are currently in VR mode.
  76746. */
  76747. get: function () {
  76748. return this._webVRpresenting || this._fullscreenVRpresenting;
  76749. },
  76750. enumerable: true,
  76751. configurable: true
  76752. });
  76753. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  76754. var vrDisplay = this._scene.getEngine().getVRDevice();
  76755. if (vrDisplay) {
  76756. var wasPresenting = this._webVRpresenting;
  76757. // A VR display is connected
  76758. this._webVRpresenting = vrDisplay.isPresenting;
  76759. if (wasPresenting && !this._webVRpresenting)
  76760. this.exitVR();
  76761. }
  76762. else {
  76763. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  76764. }
  76765. this.updateButtonVisibility();
  76766. };
  76767. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  76768. this._webVRsupported = eventArgs.vrSupported;
  76769. this._webVRready = !!eventArgs.vrDisplay;
  76770. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  76771. this.updateButtonVisibility();
  76772. };
  76773. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  76774. if (this._canvas && !this._useCustomVRButton) {
  76775. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  76776. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  76777. }
  76778. };
  76779. VRExperienceHelper.prototype.displayVRButton = function () {
  76780. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  76781. document.body.appendChild(this._btnVR);
  76782. this._btnVRDisplayed = true;
  76783. }
  76784. };
  76785. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  76786. if (!this._btnVR || this._useCustomVRButton) {
  76787. return;
  76788. }
  76789. this._btnVR.className = "babylonVRicon";
  76790. if (this.isInVRMode) {
  76791. this._btnVR.className += " vrdisplaypresenting";
  76792. }
  76793. else {
  76794. if (this._webVRready)
  76795. this._btnVR.className += " vrdisplayready";
  76796. if (this._webVRsupported)
  76797. this._btnVR.className += " vrdisplaysupported";
  76798. if (this._webVRrequesting)
  76799. this._btnVR.className += " vrdisplayrequesting";
  76800. }
  76801. };
  76802. /**
  76803. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  76804. * Otherwise, will use the fullscreen API.
  76805. */
  76806. VRExperienceHelper.prototype.enterVR = function () {
  76807. if (this.onEnteringVRObservable) {
  76808. try {
  76809. this.onEnteringVRObservable.notifyObservers(this);
  76810. }
  76811. catch (err) {
  76812. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  76813. }
  76814. }
  76815. if (this._scene.activeCamera) {
  76816. this._position = this._scene.activeCamera.position.clone();
  76817. // make sure that we return to the last active camera
  76818. this._existingCamera = this._scene.activeCamera;
  76819. }
  76820. if (this._webVRrequesting)
  76821. return;
  76822. // If WebVR is supported and a headset is connected
  76823. if (this._webVRready) {
  76824. if (!this._webVRpresenting) {
  76825. this._webVRCamera.position = this._position;
  76826. this._scene.activeCamera = this._webVRCamera;
  76827. }
  76828. }
  76829. else if (this._vrDeviceOrientationCamera) {
  76830. this._vrDeviceOrientationCamera.position = this._position;
  76831. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  76832. this._scene.getEngine().switchFullscreen(true);
  76833. this.updateButtonVisibility();
  76834. }
  76835. if (this._scene.activeCamera && this._canvas) {
  76836. this._scene.activeCamera.attachControl(this._canvas);
  76837. }
  76838. if (this._interactionsEnabled) {
  76839. this._scene.registerBeforeRender(this.beforeRender);
  76840. }
  76841. };
  76842. /**
  76843. * Attempt to exit VR, or fullscreen.
  76844. */
  76845. VRExperienceHelper.prototype.exitVR = function () {
  76846. if (this.onExitingVRObservable) {
  76847. try {
  76848. this.onExitingVRObservable.notifyObservers(this);
  76849. }
  76850. catch (err) {
  76851. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  76852. }
  76853. }
  76854. if (this._webVRpresenting) {
  76855. this._scene.getEngine().disableVR();
  76856. }
  76857. if (this._scene.activeCamera) {
  76858. this._position = this._scene.activeCamera.position.clone();
  76859. }
  76860. if (this._deviceOrientationCamera) {
  76861. this._deviceOrientationCamera.position = this._position;
  76862. this._scene.activeCamera = this._deviceOrientationCamera;
  76863. if (this._canvas) {
  76864. this._scene.activeCamera.attachControl(this._canvas);
  76865. }
  76866. }
  76867. else if (this._existingCamera) {
  76868. this._existingCamera.position = this._position;
  76869. this._scene.activeCamera = this._existingCamera;
  76870. }
  76871. this.updateButtonVisibility();
  76872. if (this._interactionsEnabled) {
  76873. this._scene.unregisterBeforeRender(this.beforeRender);
  76874. }
  76875. };
  76876. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  76877. /**
  76878. * The position of the vr experience helper.
  76879. */
  76880. get: function () {
  76881. return this._position;
  76882. },
  76883. /**
  76884. * Sets the position of the vr experience helper.
  76885. */
  76886. set: function (value) {
  76887. this._position = value;
  76888. if (this._scene.activeCamera) {
  76889. this._scene.activeCamera.position = value;
  76890. }
  76891. },
  76892. enumerable: true,
  76893. configurable: true
  76894. });
  76895. /**
  76896. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  76897. */
  76898. VRExperienceHelper.prototype.enableInteractions = function () {
  76899. var _this = this;
  76900. if (!this._interactionsEnabled) {
  76901. this._interactionsRequested = true;
  76902. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76903. this._enableInteractionOnController(this._webVRCamera.leftController);
  76904. }
  76905. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76906. this._enableInteractionOnController(this._webVRCamera.rightController);
  76907. }
  76908. this._createGazeTracker();
  76909. this.raySelectionPredicate = function (mesh) {
  76910. return mesh.isVisible;
  76911. };
  76912. this.meshSelectionPredicate = function (mesh) {
  76913. return true;
  76914. };
  76915. this._raySelectionPredicate = function (mesh) {
  76916. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  76917. && mesh.name.indexOf("teleportationTarget") === -1
  76918. && mesh.name.indexOf("torusTeleportation") === -1
  76919. && mesh.name.indexOf("laserPointer") === -1)) {
  76920. return _this.raySelectionPredicate(mesh);
  76921. }
  76922. return false;
  76923. };
  76924. this._interactionsEnabled = true;
  76925. }
  76926. };
  76927. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  76928. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  76929. if (this._floorMeshesCollection[i].id === mesh.id) {
  76930. return true;
  76931. }
  76932. }
  76933. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  76934. return true;
  76935. }
  76936. return false;
  76937. };
  76938. /**
  76939. * Adds a floor mesh to be used for teleportation.
  76940. * @param floorMesh the mesh to be used for teleportation.
  76941. */
  76942. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  76943. if (!this._floorMeshesCollection) {
  76944. return;
  76945. }
  76946. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  76947. return;
  76948. }
  76949. this._floorMeshesCollection.push(floorMesh);
  76950. };
  76951. /**
  76952. * Removes a floor mesh from being used for teleportation.
  76953. * @param floorMesh the mesh to be removed.
  76954. */
  76955. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  76956. if (!this._floorMeshesCollection) {
  76957. return;
  76958. }
  76959. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  76960. if (meshIndex !== -1) {
  76961. this._floorMeshesCollection.splice(meshIndex, 1);
  76962. }
  76963. };
  76964. /**
  76965. * Enables interactions and teleportation using the VR controllers and gaze.
  76966. * @param vrTeleportationOptions options to modify teleportation behavior.
  76967. */
  76968. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  76969. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  76970. if (!this._teleportationInitialized) {
  76971. this._teleportationRequested = true;
  76972. this.enableInteractions();
  76973. if (vrTeleportationOptions.floorMeshName) {
  76974. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  76975. }
  76976. if (vrTeleportationOptions.floorMeshes) {
  76977. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  76978. }
  76979. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76980. this._enableTeleportationOnController(this._webVRCamera.leftController);
  76981. }
  76982. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76983. this._enableTeleportationOnController(this._webVRCamera.rightController);
  76984. }
  76985. // Creates an image processing post process for the vignette not relying
  76986. // on the main scene configuration for image processing to reduce setup and spaces
  76987. // (gamma/linear) conflicts.
  76988. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  76989. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76990. imageProcessingConfiguration.vignetteEnabled = true;
  76991. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  76992. this._webVRCamera.detachPostProcess(this._postProcessMove);
  76993. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  76994. this._teleportationInitialized = true;
  76995. if (this._isDefaultTeleportationTarget) {
  76996. this._createTeleportationCircles();
  76997. }
  76998. }
  76999. };
  77000. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  77001. var _this = this;
  77002. var controllerMesh = webVRController.mesh;
  77003. if (controllerMesh) {
  77004. var makeNotPick = function (root) {
  77005. root.name += " laserPointer";
  77006. root.getChildMeshes().forEach(function (c) {
  77007. makeNotPick(c);
  77008. });
  77009. };
  77010. makeNotPick(controllerMesh);
  77011. var childMeshes = controllerMesh.getChildMeshes();
  77012. for (var i = 0; i < childMeshes.length; i++) {
  77013. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  77014. controllerMesh = childMeshes[i];
  77015. break;
  77016. }
  77017. }
  77018. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  77019. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  77020. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77021. laserPointerMaterial.alpha = 0.6;
  77022. laserPointer.material = laserPointerMaterial;
  77023. laserPointer.rotation.x = Math.PI / 2;
  77024. laserPointer.parent = controllerMesh;
  77025. laserPointer.position.z = -0.5;
  77026. laserPointer.isVisible = false;
  77027. if (webVRController.hand === "left") {
  77028. this._leftLaserPointer = laserPointer;
  77029. this._interactionsEnabledOnLeftController = true;
  77030. if (!this._rightLaserPointer) {
  77031. this._leftLaserPointer.isVisible = true;
  77032. }
  77033. }
  77034. else {
  77035. this._rightLaserPointer = laserPointer;
  77036. this._interactionsEnabledOnRightController = true;
  77037. if (!this._leftLaserPointer) {
  77038. this._rightLaserPointer.isVisible = true;
  77039. }
  77040. }
  77041. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  77042. // Enabling / disabling laserPointer
  77043. if (_this._displayLaserPointer && stateObject.value === 1) {
  77044. laserPointer.isVisible = !laserPointer.isVisible;
  77045. // Laser pointer can only be active on left or right, not both at the same time
  77046. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  77047. _this._rightLaserPointer.isVisible = false;
  77048. }
  77049. else if (_this._leftLaserPointer) {
  77050. _this._leftLaserPointer.isVisible = false;
  77051. }
  77052. }
  77053. });
  77054. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  77055. if (!_this._pointerDownOnMeshAsked) {
  77056. if (stateObject.value > _this._padSensibilityUp) {
  77057. _this._selectionPointerDown();
  77058. }
  77059. }
  77060. else if (stateObject.value < _this._padSensibilityDown) {
  77061. _this._selectionPointerUp();
  77062. }
  77063. });
  77064. }
  77065. };
  77066. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  77067. if (webVRController === void 0) { webVRController = null; }
  77068. if (!this._teleportationRequestInitiated) {
  77069. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  77070. if (webVRController) {
  77071. // If laser pointer wasn't enabled yet
  77072. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  77073. this._leftLaserPointer.isVisible = true;
  77074. if (this._rightLaserPointer) {
  77075. this._rightLaserPointer.isVisible = false;
  77076. }
  77077. }
  77078. else if (this._displayLaserPointer && this._rightLaserPointer) {
  77079. this._rightLaserPointer.isVisible = true;
  77080. if (this._leftLaserPointer) {
  77081. this._leftLaserPointer.isVisible = false;
  77082. }
  77083. }
  77084. }
  77085. this._teleportationRequestInitiated = true;
  77086. }
  77087. }
  77088. else {
  77089. // Listening to the proper controller values changes to confirm teleportation
  77090. if (webVRController == null
  77091. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  77092. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  77093. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  77094. if (this._teleportationAllowed) {
  77095. this._teleportationAllowed = false;
  77096. this._teleportCamera();
  77097. }
  77098. this._teleportationRequestInitiated = false;
  77099. }
  77100. }
  77101. }
  77102. };
  77103. VRExperienceHelper.prototype._selectionPointerDown = function () {
  77104. this._pointerDownOnMeshAsked = true;
  77105. if (this._currentMeshSelected && this._currentHit) {
  77106. this._scene.simulatePointerDown(this._currentHit);
  77107. }
  77108. };
  77109. VRExperienceHelper.prototype._selectionPointerUp = function () {
  77110. if (this._currentMeshSelected && this._currentHit) {
  77111. this._scene.simulatePointerUp(this._currentHit);
  77112. }
  77113. this._pointerDownOnMeshAsked = false;
  77114. };
  77115. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  77116. // Only rotate when user is not currently selecting a teleportation location
  77117. if (this._teleportationRequestInitiated) {
  77118. return;
  77119. }
  77120. if (!this._rotationLeftAsked) {
  77121. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  77122. this._rotationLeftAsked = true;
  77123. if (this._rotationAllowed) {
  77124. this._rotateCamera(false);
  77125. }
  77126. }
  77127. }
  77128. else {
  77129. if (stateObject.x > -this._padSensibilityDown) {
  77130. this._rotationLeftAsked = false;
  77131. }
  77132. }
  77133. if (!this._rotationRightAsked) {
  77134. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  77135. this._rotationRightAsked = true;
  77136. if (this._rotationAllowed) {
  77137. this._rotateCamera(true);
  77138. }
  77139. }
  77140. }
  77141. else {
  77142. if (stateObject.x < this._padSensibilityDown) {
  77143. this._rotationRightAsked = false;
  77144. }
  77145. }
  77146. };
  77147. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  77148. // Only teleport backwards when user is not currently selecting a teleportation location
  77149. if (this._teleportationRequestInitiated) {
  77150. return;
  77151. }
  77152. // Teleport backwards
  77153. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  77154. if (!this._teleportationBackRequestInitiated) {
  77155. if (!this.currentVRCamera) {
  77156. return;
  77157. }
  77158. // Get rotation and position of the current camera
  77159. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  77160. var position = this.currentVRCamera.position;
  77161. // If the camera has device position, use that instead
  77162. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  77163. rotation = this.currentVRCamera.deviceRotationQuaternion;
  77164. position = this.currentVRCamera.devicePosition;
  77165. }
  77166. // Get matrix with only the y rotation of the device rotation
  77167. rotation.toEulerAnglesToRef(this._workingVector);
  77168. this._workingVector.z = 0;
  77169. this._workingVector.x = 0;
  77170. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  77171. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  77172. // Rotate backwards ray by device rotation to cast at the ground behind the user
  77173. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  77174. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  77175. var ray = new BABYLON.Ray(position, this._workingVector);
  77176. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77177. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  77178. this._teleportCamera(hit.pickedPoint);
  77179. }
  77180. this._teleportationBackRequestInitiated = true;
  77181. }
  77182. }
  77183. else {
  77184. this._teleportationBackRequestInitiated = false;
  77185. }
  77186. };
  77187. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  77188. var _this = this;
  77189. var controllerMesh = webVRController.mesh;
  77190. if (controllerMesh) {
  77191. if (webVRController.hand === "left") {
  77192. if (!this._interactionsEnabledOnLeftController) {
  77193. this._enableInteractionOnController(webVRController);
  77194. }
  77195. this._teleportationEnabledOnLeftController = true;
  77196. }
  77197. else {
  77198. if (!this._interactionsEnabledOnRightController) {
  77199. this._enableInteractionOnController(webVRController);
  77200. }
  77201. this._teleportationEnabledOnRightController = true;
  77202. }
  77203. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  77204. this._dpadPressed = false;
  77205. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  77206. _this._dpadPressed = stateObject.pressed;
  77207. if (!_this._dpadPressed) {
  77208. _this._rotationLeftAsked = false;
  77209. _this._rotationRightAsked = false;
  77210. _this._teleportationBackRequestInitiated = false;
  77211. }
  77212. });
  77213. }
  77214. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  77215. if (_this.teleportationEnabled) {
  77216. _this._checkTeleportBackwards(stateObject);
  77217. _this._checkTeleportWithRay(stateObject, webVRController);
  77218. }
  77219. _this._checkRotate(stateObject);
  77220. });
  77221. }
  77222. };
  77223. // Gaze support used to point to teleport or to interact with an object
  77224. VRExperienceHelper.prototype._createGazeTracker = function () {
  77225. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  77226. this._gazeTracker.bakeCurrentTransformIntoVertices();
  77227. this._gazeTracker.isPickable = false;
  77228. this._gazeTracker.isVisible = false;
  77229. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  77230. targetMat.specularColor = BABYLON.Color3.Black();
  77231. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  77232. targetMat.backFaceCulling = false;
  77233. this._gazeTracker.material = targetMat;
  77234. };
  77235. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  77236. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  77237. this._teleportationTarget.isPickable = false;
  77238. var length = 512;
  77239. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  77240. dynamicTexture.hasAlpha = true;
  77241. var context = dynamicTexture.getContext();
  77242. var centerX = length / 2;
  77243. var centerY = length / 2;
  77244. var radius = 200;
  77245. context.beginPath();
  77246. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  77247. context.fillStyle = this._teleportationFillColor;
  77248. context.fill();
  77249. context.lineWidth = 10;
  77250. context.strokeStyle = this._teleportationBorderColor;
  77251. context.stroke();
  77252. context.closePath();
  77253. dynamicTexture.update();
  77254. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  77255. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  77256. this._teleportationTarget.material = teleportationCircleMaterial;
  77257. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  77258. torus.isPickable = false;
  77259. torus.parent = this._teleportationTarget;
  77260. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  77261. var keys = [];
  77262. keys.push({
  77263. frame: 0,
  77264. value: 0
  77265. });
  77266. keys.push({
  77267. frame: 30,
  77268. value: 0.4
  77269. });
  77270. keys.push({
  77271. frame: 60,
  77272. value: 0
  77273. });
  77274. animationInnerCircle.setKeys(keys);
  77275. var easingFunction = new BABYLON.SineEase();
  77276. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  77277. animationInnerCircle.setEasingFunction(easingFunction);
  77278. torus.animations = [];
  77279. torus.animations.push(animationInnerCircle);
  77280. this._scene.beginAnimation(torus, 0, 60, true);
  77281. this._hideTeleportationTarget();
  77282. };
  77283. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  77284. if (this._teleportationInitialized) {
  77285. this._teleportationTarget.isVisible = true;
  77286. if (this._isDefaultTeleportationTarget) {
  77287. this._teleportationTarget.getChildren()[0].isVisible = true;
  77288. }
  77289. }
  77290. };
  77291. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  77292. if (this._teleportationInitialized) {
  77293. this._teleportationTarget.isVisible = false;
  77294. if (this._isDefaultTeleportationTarget) {
  77295. this._teleportationTarget.getChildren()[0].isVisible = false;
  77296. }
  77297. }
  77298. };
  77299. VRExperienceHelper.prototype._rotateCamera = function (right) {
  77300. var _this = this;
  77301. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77302. return;
  77303. }
  77304. if (right) {
  77305. this._rotationAngle++;
  77306. }
  77307. else {
  77308. this._rotationAngle--;
  77309. }
  77310. this.currentVRCamera.animations = [];
  77311. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  77312. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77313. var animationRotationKeys = [];
  77314. animationRotationKeys.push({
  77315. frame: 0,
  77316. value: this.currentVRCamera.rotationQuaternion
  77317. });
  77318. animationRotationKeys.push({
  77319. frame: 6,
  77320. value: target
  77321. });
  77322. animationRotation.setKeys(animationRotationKeys);
  77323. animationRotation.setEasingFunction(this._circleEase);
  77324. this.currentVRCamera.animations.push(animationRotation);
  77325. this._postProcessMove.animations = [];
  77326. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77327. var vignetteWeightKeys = [];
  77328. vignetteWeightKeys.push({
  77329. frame: 0,
  77330. value: 0
  77331. });
  77332. vignetteWeightKeys.push({
  77333. frame: 3,
  77334. value: 4
  77335. });
  77336. vignetteWeightKeys.push({
  77337. frame: 6,
  77338. value: 0
  77339. });
  77340. animationPP.setKeys(vignetteWeightKeys);
  77341. animationPP.setEasingFunction(this._circleEase);
  77342. this._postProcessMove.animations.push(animationPP);
  77343. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77344. var vignetteStretchKeys = [];
  77345. vignetteStretchKeys.push({
  77346. frame: 0,
  77347. value: 0
  77348. });
  77349. vignetteStretchKeys.push({
  77350. frame: 3,
  77351. value: 10
  77352. });
  77353. vignetteStretchKeys.push({
  77354. frame: 6,
  77355. value: 0
  77356. });
  77357. animationPP2.setKeys(vignetteStretchKeys);
  77358. animationPP2.setEasingFunction(this._circleEase);
  77359. this._postProcessMove.animations.push(animationPP2);
  77360. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77361. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77362. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77363. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  77364. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77365. });
  77366. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  77367. };
  77368. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  77369. if (hit.pickedPoint) {
  77370. this._teleportationAllowed = true;
  77371. if (this._teleportationRequestInitiated) {
  77372. this._displayTeleportationTarget();
  77373. }
  77374. else {
  77375. this._hideTeleportationTarget();
  77376. }
  77377. this._haloCenter.copyFrom(hit.pickedPoint);
  77378. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  77379. var pickNormal = hit.getNormal(true, false);
  77380. if (pickNormal) {
  77381. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77382. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77383. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  77384. }
  77385. this._teleportationTarget.position.y += 0.1;
  77386. }
  77387. };
  77388. VRExperienceHelper.prototype._teleportCamera = function (location) {
  77389. var _this = this;
  77390. if (location === void 0) { location = null; }
  77391. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77392. return;
  77393. }
  77394. if (!location) {
  77395. location = this._haloCenter;
  77396. }
  77397. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  77398. // offset of the headset from the anchor.
  77399. if (this.webVRCamera.leftCamera) {
  77400. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  77401. this._workingVector.subtractInPlace(this.webVRCamera.position);
  77402. location.subtractToRef(this._workingVector, this._workingVector);
  77403. }
  77404. else {
  77405. this._workingVector.copyFrom(location);
  77406. }
  77407. // Add height to account for user's height offset
  77408. if (this.isInVRMode) {
  77409. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  77410. }
  77411. else {
  77412. this._workingVector.y += this._defaultHeight;
  77413. }
  77414. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  77415. // Create animation from the camera's position to the new location
  77416. this.currentVRCamera.animations = [];
  77417. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77418. var animationCameraTeleportationKeys = [{
  77419. frame: 0,
  77420. value: this.currentVRCamera.position
  77421. },
  77422. {
  77423. frame: 11,
  77424. value: this._workingVector
  77425. }
  77426. ];
  77427. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  77428. animationCameraTeleportation.setEasingFunction(this._circleEase);
  77429. this.currentVRCamera.animations.push(animationCameraTeleportation);
  77430. this._postProcessMove.animations = [];
  77431. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77432. var vignetteWeightKeys = [];
  77433. vignetteWeightKeys.push({
  77434. frame: 0,
  77435. value: 0
  77436. });
  77437. vignetteWeightKeys.push({
  77438. frame: 5,
  77439. value: 8
  77440. });
  77441. vignetteWeightKeys.push({
  77442. frame: 11,
  77443. value: 0
  77444. });
  77445. animationPP.setKeys(vignetteWeightKeys);
  77446. this._postProcessMove.animations.push(animationPP);
  77447. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  77448. var vignetteStretchKeys = [];
  77449. vignetteStretchKeys.push({
  77450. frame: 0,
  77451. value: 0
  77452. });
  77453. vignetteStretchKeys.push({
  77454. frame: 5,
  77455. value: 10
  77456. });
  77457. vignetteStretchKeys.push({
  77458. frame: 11,
  77459. value: 0
  77460. });
  77461. animationPP2.setKeys(vignetteStretchKeys);
  77462. this._postProcessMove.animations.push(animationPP2);
  77463. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  77464. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  77465. this._webVRCamera.attachPostProcess(this._postProcessMove);
  77466. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  77467. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  77468. });
  77469. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  77470. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  77471. });
  77472. };
  77473. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  77474. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  77475. return;
  77476. }
  77477. var ray;
  77478. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  77479. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  77480. }
  77481. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  77482. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  77483. }
  77484. else {
  77485. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  77486. }
  77487. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  77488. // Moving the gazeTracker on the mesh face targetted
  77489. if (hit && hit.pickedPoint) {
  77490. if (this._displayGaze) {
  77491. var multiplier = 1;
  77492. this._gazeTracker.isVisible = true;
  77493. if (this._isActionableMesh) {
  77494. multiplier = 3;
  77495. }
  77496. this._gazeTracker.scaling.x = hit.distance * multiplier;
  77497. this._gazeTracker.scaling.y = hit.distance * multiplier;
  77498. this._gazeTracker.scaling.z = hit.distance * multiplier;
  77499. var pickNormal = hit.getNormal();
  77500. // To avoid z-fighting
  77501. var deltaFighting = 0.002;
  77502. if (pickNormal) {
  77503. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  77504. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  77505. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  77506. }
  77507. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  77508. if (this._gazeTracker.position.x < 0) {
  77509. this._gazeTracker.position.x += deltaFighting;
  77510. }
  77511. else {
  77512. this._gazeTracker.position.x -= deltaFighting;
  77513. }
  77514. if (this._gazeTracker.position.y < 0) {
  77515. this._gazeTracker.position.y += deltaFighting;
  77516. }
  77517. else {
  77518. this._gazeTracker.position.y -= deltaFighting;
  77519. }
  77520. if (this._gazeTracker.position.z < 0) {
  77521. this._gazeTracker.position.z += deltaFighting;
  77522. }
  77523. else {
  77524. this._gazeTracker.position.z -= deltaFighting;
  77525. }
  77526. }
  77527. // Changing the size of the laser pointer based on the distance from the targetted point
  77528. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  77529. this._rightLaserPointer.scaling.y = hit.distance;
  77530. this._rightLaserPointer.position.z = -hit.distance / 2;
  77531. }
  77532. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  77533. this._leftLaserPointer.scaling.y = hit.distance;
  77534. this._leftLaserPointer.position.z = -hit.distance / 2;
  77535. }
  77536. }
  77537. else {
  77538. this._gazeTracker.isVisible = false;
  77539. }
  77540. if (hit && hit.pickedMesh) {
  77541. this._currentHit = hit;
  77542. if (this._pointerDownOnMeshAsked) {
  77543. this._scene.simulatePointerMove(this._currentHit);
  77544. }
  77545. // The object selected is the floor, we're in a teleportation scenario
  77546. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  77547. // Moving the teleportation area to this targetted point
  77548. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  77549. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  77550. this._notifySelectedMeshUnselected();
  77551. }
  77552. this._currentMeshSelected = null;
  77553. this._moveTeleportationSelectorTo(hit);
  77554. return;
  77555. }
  77556. // If not, we're in a selection scenario
  77557. this._hideTeleportationTarget();
  77558. this._teleportationAllowed = false;
  77559. if (hit.pickedMesh !== this._currentMeshSelected) {
  77560. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  77561. this.onNewMeshPicked.notifyObservers(hit);
  77562. this._currentMeshSelected = hit.pickedMesh;
  77563. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  77564. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  77565. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  77566. this._isActionableMesh = true;
  77567. }
  77568. else {
  77569. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77570. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77571. this._isActionableMesh = false;
  77572. }
  77573. try {
  77574. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  77575. }
  77576. catch (err) {
  77577. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  77578. }
  77579. }
  77580. else {
  77581. this._notifySelectedMeshUnselected();
  77582. this._currentMeshSelected = null;
  77583. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77584. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77585. }
  77586. }
  77587. }
  77588. else {
  77589. this._currentHit = null;
  77590. this._notifySelectedMeshUnselected();
  77591. this._currentMeshSelected = null;
  77592. this._teleportationAllowed = false;
  77593. this._hideTeleportationTarget();
  77594. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77595. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  77596. }
  77597. };
  77598. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  77599. if (this._currentMeshSelected) {
  77600. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  77601. }
  77602. };
  77603. /**
  77604. * Sets the color of the laser ray from the vr controllers.
  77605. * @param color new color for the ray.
  77606. */
  77607. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  77608. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  77609. this._leftLaserPointer.material.emissiveColor = color;
  77610. }
  77611. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  77612. this._rightLaserPointer.material.emissiveColor = color;
  77613. }
  77614. };
  77615. /**
  77616. * Sets the color of the ray from the vr headsets gaze.
  77617. * @param color new color for the ray.
  77618. */
  77619. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  77620. if (this._gazeTracker.material) {
  77621. this._gazeTracker.material.emissiveColor = color;
  77622. }
  77623. };
  77624. /**
  77625. * Exits VR and disposes of the vr experience helper
  77626. */
  77627. VRExperienceHelper.prototype.dispose = function () {
  77628. if (this.isInVRMode) {
  77629. this.exitVR();
  77630. }
  77631. if (this._passProcessMove) {
  77632. this._passProcessMove.dispose();
  77633. }
  77634. if (this._postProcessMove) {
  77635. this._postProcessMove.dispose();
  77636. }
  77637. if (this._webVRCamera) {
  77638. this._webVRCamera.dispose();
  77639. }
  77640. if (this._vrDeviceOrientationCamera) {
  77641. this._vrDeviceOrientationCamera.dispose();
  77642. }
  77643. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  77644. document.body.removeChild(this._btnVR);
  77645. }
  77646. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  77647. this._deviceOrientationCamera.dispose();
  77648. }
  77649. if (this._gazeTracker) {
  77650. this._gazeTracker.dispose();
  77651. }
  77652. if (this._teleportationTarget) {
  77653. this._teleportationTarget.dispose();
  77654. }
  77655. this._floorMeshesCollection = [];
  77656. document.removeEventListener("keydown", this._onKeyDown);
  77657. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77658. window.removeEventListener("resize", this._onResize);
  77659. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  77660. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  77661. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  77662. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  77663. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  77664. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  77665. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  77666. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77667. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  77668. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  77669. this._scene.unregisterBeforeRender(this.beforeRender);
  77670. };
  77671. /**
  77672. * Gets the name of the VRExperienceHelper class
  77673. * @returns "VRExperienceHelper"
  77674. */
  77675. VRExperienceHelper.prototype.getClassName = function () {
  77676. return "VRExperienceHelper";
  77677. };
  77678. return VRExperienceHelper;
  77679. }());
  77680. BABYLON.VRExperienceHelper = VRExperienceHelper;
  77681. })(BABYLON || (BABYLON = {}));
  77682. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  77683. // Mainly based on these 2 articles :
  77684. // 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
  77685. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  77686. var BABYLON;
  77687. (function (BABYLON) {
  77688. var JoystickAxis;
  77689. (function (JoystickAxis) {
  77690. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  77691. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  77692. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  77693. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  77694. var VirtualJoystick = /** @class */ (function () {
  77695. function VirtualJoystick(leftJoystick) {
  77696. var _this = this;
  77697. if (leftJoystick) {
  77698. this._leftJoystick = true;
  77699. }
  77700. else {
  77701. this._leftJoystick = false;
  77702. }
  77703. VirtualJoystick._globalJoystickIndex++;
  77704. // By default left & right arrow keys are moving the X
  77705. // and up & down keys are moving the Y
  77706. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77707. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77708. this.reverseLeftRight = false;
  77709. this.reverseUpDown = false;
  77710. // collections of pointers
  77711. this._touches = new BABYLON.StringDictionary();
  77712. this.deltaPosition = BABYLON.Vector3.Zero();
  77713. this._joystickSensibility = 25;
  77714. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  77715. this._onResize = function (evt) {
  77716. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77717. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77718. if (VirtualJoystick.vjCanvas) {
  77719. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  77720. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  77721. }
  77722. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  77723. };
  77724. // injecting a canvas element on top of the canvas 3D game
  77725. if (!VirtualJoystick.vjCanvas) {
  77726. window.addEventListener("resize", this._onResize, false);
  77727. VirtualJoystick.vjCanvas = document.createElement("canvas");
  77728. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77729. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77730. VirtualJoystick.vjCanvas.width = window.innerWidth;
  77731. VirtualJoystick.vjCanvas.height = window.innerHeight;
  77732. VirtualJoystick.vjCanvas.style.width = "100%";
  77733. VirtualJoystick.vjCanvas.style.height = "100%";
  77734. VirtualJoystick.vjCanvas.style.position = "absolute";
  77735. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  77736. VirtualJoystick.vjCanvas.style.top = "0px";
  77737. VirtualJoystick.vjCanvas.style.left = "0px";
  77738. VirtualJoystick.vjCanvas.style.zIndex = "5";
  77739. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  77740. // Support for jQuery PEP polyfill
  77741. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  77742. var context = VirtualJoystick.vjCanvas.getContext('2d');
  77743. if (!context) {
  77744. throw new Error("Unable to create canvas for virtual joystick");
  77745. }
  77746. VirtualJoystick.vjCanvasContext = context;
  77747. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  77748. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77749. document.body.appendChild(VirtualJoystick.vjCanvas);
  77750. }
  77751. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  77752. this.pressed = false;
  77753. // default joystick color
  77754. this._joystickColor = "cyan";
  77755. this._joystickPointerID = -1;
  77756. // current joystick position
  77757. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  77758. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  77759. // origin joystick position
  77760. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  77761. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  77762. this._onPointerDownHandlerRef = function (evt) {
  77763. _this._onPointerDown(evt);
  77764. };
  77765. this._onPointerMoveHandlerRef = function (evt) {
  77766. _this._onPointerMove(evt);
  77767. };
  77768. this._onPointerUpHandlerRef = function (evt) {
  77769. _this._onPointerUp(evt);
  77770. };
  77771. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  77772. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  77773. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  77774. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  77775. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  77776. evt.preventDefault(); // Disables system menu
  77777. }, false);
  77778. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77779. }
  77780. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  77781. this._joystickSensibility = newJoystickSensibility;
  77782. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  77783. };
  77784. VirtualJoystick.prototype._onPointerDown = function (e) {
  77785. var positionOnScreenCondition;
  77786. e.preventDefault();
  77787. if (this._leftJoystick === true) {
  77788. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  77789. }
  77790. else {
  77791. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  77792. }
  77793. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  77794. // First contact will be dedicated to the virtual joystick
  77795. this._joystickPointerID = e.pointerId;
  77796. this._joystickPointerStartPos.x = e.clientX;
  77797. this._joystickPointerStartPos.y = e.clientY;
  77798. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  77799. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  77800. this._deltaJoystickVector.x = 0;
  77801. this._deltaJoystickVector.y = 0;
  77802. this.pressed = true;
  77803. this._touches.add(e.pointerId.toString(), e);
  77804. }
  77805. else {
  77806. // You can only trigger the action buttons with a joystick declared
  77807. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  77808. this._action();
  77809. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  77810. }
  77811. }
  77812. };
  77813. VirtualJoystick.prototype._onPointerMove = function (e) {
  77814. // If the current pointer is the one associated to the joystick (first touch contact)
  77815. if (this._joystickPointerID == e.pointerId) {
  77816. this._joystickPointerPos.x = e.clientX;
  77817. this._joystickPointerPos.y = e.clientY;
  77818. this._deltaJoystickVector = this._joystickPointerPos.clone();
  77819. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  77820. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  77821. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  77822. switch (this._axisTargetedByLeftAndRight) {
  77823. case JoystickAxis.X:
  77824. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  77825. break;
  77826. case JoystickAxis.Y:
  77827. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  77828. break;
  77829. case JoystickAxis.Z:
  77830. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  77831. break;
  77832. }
  77833. var directionUpDown = this.reverseUpDown ? 1 : -1;
  77834. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  77835. switch (this._axisTargetedByUpAndDown) {
  77836. case JoystickAxis.X:
  77837. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  77838. break;
  77839. case JoystickAxis.Y:
  77840. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  77841. break;
  77842. case JoystickAxis.Z:
  77843. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  77844. break;
  77845. }
  77846. }
  77847. else {
  77848. var data = this._touches.get(e.pointerId.toString());
  77849. if (data) {
  77850. data.x = e.clientX;
  77851. data.y = e.clientY;
  77852. }
  77853. }
  77854. };
  77855. VirtualJoystick.prototype._onPointerUp = function (e) {
  77856. if (this._joystickPointerID == e.pointerId) {
  77857. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  77858. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  77859. this._joystickPointerID = -1;
  77860. this.pressed = false;
  77861. }
  77862. else {
  77863. var touch = this._touches.get(e.pointerId.toString());
  77864. if (touch) {
  77865. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77866. }
  77867. }
  77868. this._deltaJoystickVector.x = 0;
  77869. this._deltaJoystickVector.y = 0;
  77870. this._touches.remove(e.pointerId.toString());
  77871. };
  77872. /**
  77873. * Change the color of the virtual joystick
  77874. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  77875. */
  77876. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  77877. this._joystickColor = newColor;
  77878. };
  77879. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  77880. this._action = action;
  77881. };
  77882. // Define which axis you'd like to control for left & right
  77883. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  77884. switch (axis) {
  77885. case JoystickAxis.X:
  77886. case JoystickAxis.Y:
  77887. case JoystickAxis.Z:
  77888. this._axisTargetedByLeftAndRight = axis;
  77889. break;
  77890. default:
  77891. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77892. break;
  77893. }
  77894. };
  77895. // Define which axis you'd like to control for up & down
  77896. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  77897. switch (axis) {
  77898. case JoystickAxis.X:
  77899. case JoystickAxis.Y:
  77900. case JoystickAxis.Z:
  77901. this._axisTargetedByUpAndDown = axis;
  77902. break;
  77903. default:
  77904. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77905. break;
  77906. }
  77907. };
  77908. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  77909. var _this = this;
  77910. if (this.pressed) {
  77911. this._touches.forEach(function (key, touch) {
  77912. if (touch.pointerId === _this._joystickPointerID) {
  77913. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  77914. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  77915. VirtualJoystick.vjCanvasContext.beginPath();
  77916. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77917. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77918. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  77919. VirtualJoystick.vjCanvasContext.stroke();
  77920. VirtualJoystick.vjCanvasContext.closePath();
  77921. VirtualJoystick.vjCanvasContext.beginPath();
  77922. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77923. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77924. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  77925. VirtualJoystick.vjCanvasContext.stroke();
  77926. VirtualJoystick.vjCanvasContext.closePath();
  77927. VirtualJoystick.vjCanvasContext.beginPath();
  77928. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77929. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  77930. VirtualJoystick.vjCanvasContext.stroke();
  77931. VirtualJoystick.vjCanvasContext.closePath();
  77932. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  77933. }
  77934. else {
  77935. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77936. VirtualJoystick.vjCanvasContext.beginPath();
  77937. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  77938. VirtualJoystick.vjCanvasContext.beginPath();
  77939. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  77940. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77941. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  77942. VirtualJoystick.vjCanvasContext.stroke();
  77943. VirtualJoystick.vjCanvasContext.closePath();
  77944. touch.prevX = touch.x;
  77945. touch.prevY = touch.y;
  77946. }
  77947. ;
  77948. });
  77949. }
  77950. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77951. };
  77952. VirtualJoystick.prototype.releaseCanvas = function () {
  77953. if (VirtualJoystick.vjCanvas) {
  77954. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  77955. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  77956. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  77957. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  77958. window.removeEventListener("resize", this._onResize);
  77959. document.body.removeChild(VirtualJoystick.vjCanvas);
  77960. VirtualJoystick.vjCanvas = null;
  77961. }
  77962. };
  77963. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  77964. VirtualJoystick._globalJoystickIndex = 0;
  77965. return VirtualJoystick;
  77966. }());
  77967. BABYLON.VirtualJoystick = VirtualJoystick;
  77968. })(BABYLON || (BABYLON = {}));
  77969. //# sourceMappingURL=babylon.virtualJoystick.js.map
  77970. var BABYLON;
  77971. (function (BABYLON) {
  77972. // We're mainly based on the logic defined into the FreeCamera code
  77973. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  77974. __extends(VirtualJoysticksCamera, _super);
  77975. function VirtualJoysticksCamera(name, position, scene) {
  77976. var _this = _super.call(this, name, position, scene) || this;
  77977. _this.inputs.addVirtualJoystick();
  77978. return _this;
  77979. }
  77980. VirtualJoysticksCamera.prototype.getClassName = function () {
  77981. return "VirtualJoysticksCamera";
  77982. };
  77983. return VirtualJoysticksCamera;
  77984. }(BABYLON.FreeCamera));
  77985. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  77986. })(BABYLON || (BABYLON = {}));
  77987. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  77988. var BABYLON;
  77989. (function (BABYLON) {
  77990. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  77991. function FreeCameraVirtualJoystickInput() {
  77992. }
  77993. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  77994. return this._leftjoystick;
  77995. };
  77996. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  77997. return this._rightjoystick;
  77998. };
  77999. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  78000. if (this._leftjoystick) {
  78001. var camera = this.camera;
  78002. var speed = camera._computeLocalCameraSpeed() * 50;
  78003. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  78004. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  78005. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  78006. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  78007. if (!this._leftjoystick.pressed) {
  78008. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  78009. }
  78010. if (!this._rightjoystick.pressed) {
  78011. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  78012. }
  78013. }
  78014. };
  78015. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  78016. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  78017. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  78018. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  78019. this._leftjoystick.setJoystickSensibility(0.15);
  78020. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  78021. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  78022. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  78023. this._rightjoystick.reverseUpDown = true;
  78024. this._rightjoystick.setJoystickSensibility(0.05);
  78025. this._rightjoystick.setJoystickColor("yellow");
  78026. };
  78027. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  78028. this._leftjoystick.releaseCanvas();
  78029. this._rightjoystick.releaseCanvas();
  78030. };
  78031. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  78032. return "FreeCameraVirtualJoystickInput";
  78033. };
  78034. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  78035. return "virtualJoystick";
  78036. };
  78037. return FreeCameraVirtualJoystickInput;
  78038. }());
  78039. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  78040. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  78041. })(BABYLON || (BABYLON = {}));
  78042. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  78043. var BABYLON;
  78044. (function (BABYLON) {
  78045. var SimplificationSettings = /** @class */ (function () {
  78046. function SimplificationSettings(quality, distance, optimizeMesh) {
  78047. this.quality = quality;
  78048. this.distance = distance;
  78049. this.optimizeMesh = optimizeMesh;
  78050. }
  78051. return SimplificationSettings;
  78052. }());
  78053. BABYLON.SimplificationSettings = SimplificationSettings;
  78054. var SimplificationQueue = /** @class */ (function () {
  78055. function SimplificationQueue() {
  78056. this.running = false;
  78057. this._simplificationArray = [];
  78058. }
  78059. SimplificationQueue.prototype.addTask = function (task) {
  78060. this._simplificationArray.push(task);
  78061. };
  78062. SimplificationQueue.prototype.executeNext = function () {
  78063. var task = this._simplificationArray.pop();
  78064. if (task) {
  78065. this.running = true;
  78066. this.runSimplification(task);
  78067. }
  78068. else {
  78069. this.running = false;
  78070. }
  78071. };
  78072. SimplificationQueue.prototype.runSimplification = function (task) {
  78073. var _this = this;
  78074. if (task.parallelProcessing) {
  78075. //parallel simplifier
  78076. task.settings.forEach(function (setting) {
  78077. var simplifier = _this.getSimplifier(task);
  78078. simplifier.simplify(setting, function (newMesh) {
  78079. task.mesh.addLODLevel(setting.distance, newMesh);
  78080. newMesh.isVisible = true;
  78081. //check if it is the last
  78082. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  78083. //all done, run the success callback.
  78084. task.successCallback();
  78085. }
  78086. _this.executeNext();
  78087. });
  78088. });
  78089. }
  78090. else {
  78091. //single simplifier.
  78092. var simplifier = this.getSimplifier(task);
  78093. var runDecimation = function (setting, callback) {
  78094. simplifier.simplify(setting, function (newMesh) {
  78095. task.mesh.addLODLevel(setting.distance, newMesh);
  78096. newMesh.isVisible = true;
  78097. //run the next quality level
  78098. callback();
  78099. });
  78100. };
  78101. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  78102. runDecimation(task.settings[loop.index], function () {
  78103. loop.executeNext();
  78104. });
  78105. }, function () {
  78106. //execution ended, run the success callback.
  78107. if (task.successCallback) {
  78108. task.successCallback();
  78109. }
  78110. _this.executeNext();
  78111. });
  78112. }
  78113. };
  78114. SimplificationQueue.prototype.getSimplifier = function (task) {
  78115. switch (task.simplificationType) {
  78116. case SimplificationType.QUADRATIC:
  78117. default:
  78118. return new QuadraticErrorSimplification(task.mesh);
  78119. }
  78120. };
  78121. return SimplificationQueue;
  78122. }());
  78123. BABYLON.SimplificationQueue = SimplificationQueue;
  78124. /**
  78125. * The implemented types of simplification.
  78126. * At the moment only Quadratic Error Decimation is implemented.
  78127. */
  78128. var SimplificationType;
  78129. (function (SimplificationType) {
  78130. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  78131. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  78132. var DecimationTriangle = /** @class */ (function () {
  78133. function DecimationTriangle(vertices) {
  78134. this.vertices = vertices;
  78135. this.error = new Array(4);
  78136. this.deleted = false;
  78137. this.isDirty = false;
  78138. this.deletePending = false;
  78139. this.borderFactor = 0;
  78140. }
  78141. return DecimationTriangle;
  78142. }());
  78143. BABYLON.DecimationTriangle = DecimationTriangle;
  78144. var DecimationVertex = /** @class */ (function () {
  78145. function DecimationVertex(position, id) {
  78146. this.position = position;
  78147. this.id = id;
  78148. this.isBorder = true;
  78149. this.q = new QuadraticMatrix();
  78150. this.triangleCount = 0;
  78151. this.triangleStart = 0;
  78152. this.originalOffsets = [];
  78153. }
  78154. DecimationVertex.prototype.updatePosition = function (newPosition) {
  78155. this.position.copyFrom(newPosition);
  78156. };
  78157. return DecimationVertex;
  78158. }());
  78159. BABYLON.DecimationVertex = DecimationVertex;
  78160. var QuadraticMatrix = /** @class */ (function () {
  78161. function QuadraticMatrix(data) {
  78162. this.data = new Array(10);
  78163. for (var i = 0; i < 10; ++i) {
  78164. if (data && data[i]) {
  78165. this.data[i] = data[i];
  78166. }
  78167. else {
  78168. this.data[i] = 0;
  78169. }
  78170. }
  78171. }
  78172. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  78173. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  78174. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  78175. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  78176. return det;
  78177. };
  78178. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  78179. for (var i = 0; i < 10; ++i) {
  78180. this.data[i] += matrix.data[i];
  78181. }
  78182. };
  78183. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  78184. for (var i = 0; i < 10; ++i) {
  78185. this.data[i] += data[i];
  78186. }
  78187. };
  78188. QuadraticMatrix.prototype.add = function (matrix) {
  78189. var m = new QuadraticMatrix();
  78190. for (var i = 0; i < 10; ++i) {
  78191. m.data[i] = this.data[i] + matrix.data[i];
  78192. }
  78193. return m;
  78194. };
  78195. QuadraticMatrix.FromData = function (a, b, c, d) {
  78196. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  78197. };
  78198. //returning an array to avoid garbage collection
  78199. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  78200. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  78201. };
  78202. return QuadraticMatrix;
  78203. }());
  78204. BABYLON.QuadraticMatrix = QuadraticMatrix;
  78205. var Reference = /** @class */ (function () {
  78206. function Reference(vertexId, triangleId) {
  78207. this.vertexId = vertexId;
  78208. this.triangleId = triangleId;
  78209. }
  78210. return Reference;
  78211. }());
  78212. BABYLON.Reference = Reference;
  78213. /**
  78214. * An implementation of the Quadratic Error simplification algorithm.
  78215. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  78216. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  78217. * @author RaananW
  78218. */
  78219. var QuadraticErrorSimplification = /** @class */ (function () {
  78220. function QuadraticErrorSimplification(_mesh) {
  78221. this._mesh = _mesh;
  78222. this.syncIterations = 5000;
  78223. this.aggressiveness = 7;
  78224. this.decimationIterations = 100;
  78225. this.boundingBoxEpsilon = BABYLON.Epsilon;
  78226. }
  78227. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  78228. var _this = this;
  78229. this.initDecimatedMesh();
  78230. //iterating through the submeshes array, one after the other.
  78231. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  78232. _this.initWithMesh(loop.index, function () {
  78233. _this.runDecimation(settings, loop.index, function () {
  78234. loop.executeNext();
  78235. });
  78236. }, settings.optimizeMesh);
  78237. }, function () {
  78238. setTimeout(function () {
  78239. successCallback(_this._reconstructedMesh);
  78240. }, 0);
  78241. });
  78242. };
  78243. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  78244. var _this = this;
  78245. var targetCount = ~~(this.triangles.length * settings.quality);
  78246. var deletedTriangles = 0;
  78247. var triangleCount = this.triangles.length;
  78248. var iterationFunction = function (iteration, callback) {
  78249. setTimeout(function () {
  78250. if (iteration % 5 === 0) {
  78251. _this.updateMesh(iteration === 0);
  78252. }
  78253. for (var i = 0; i < _this.triangles.length; ++i) {
  78254. _this.triangles[i].isDirty = false;
  78255. }
  78256. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  78257. var trianglesIterator = function (i) {
  78258. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  78259. var t = _this.triangles[tIdx];
  78260. if (!t)
  78261. return;
  78262. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  78263. return;
  78264. }
  78265. for (var j = 0; j < 3; ++j) {
  78266. if (t.error[j] < threshold) {
  78267. var deleted0 = [];
  78268. var deleted1 = [];
  78269. var v0 = t.vertices[j];
  78270. var v1 = t.vertices[(j + 1) % 3];
  78271. if (v0.isBorder || v1.isBorder)
  78272. continue;
  78273. var p = BABYLON.Vector3.Zero();
  78274. var n = BABYLON.Vector3.Zero();
  78275. var uv = BABYLON.Vector2.Zero();
  78276. var color = new BABYLON.Color4(0, 0, 0, 1);
  78277. _this.calculateError(v0, v1, p, n, uv, color);
  78278. var delTr = new Array();
  78279. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  78280. continue;
  78281. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  78282. continue;
  78283. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  78284. continue;
  78285. var uniqueArray = new Array();
  78286. delTr.forEach(function (deletedT) {
  78287. if (uniqueArray.indexOf(deletedT) === -1) {
  78288. deletedT.deletePending = true;
  78289. uniqueArray.push(deletedT);
  78290. }
  78291. });
  78292. if (uniqueArray.length % 2 !== 0) {
  78293. continue;
  78294. }
  78295. v0.q = v1.q.add(v0.q);
  78296. v0.updatePosition(p);
  78297. var tStart = _this.references.length;
  78298. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  78299. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  78300. var tCount = _this.references.length - tStart;
  78301. if (tCount <= v0.triangleCount) {
  78302. if (tCount) {
  78303. for (var c = 0; c < tCount; c++) {
  78304. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  78305. }
  78306. }
  78307. }
  78308. else {
  78309. v0.triangleStart = tStart;
  78310. }
  78311. v0.triangleCount = tCount;
  78312. break;
  78313. }
  78314. }
  78315. };
  78316. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  78317. }, 0);
  78318. };
  78319. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  78320. if (triangleCount - deletedTriangles <= targetCount)
  78321. loop.breakLoop();
  78322. else {
  78323. iterationFunction(loop.index, function () {
  78324. loop.executeNext();
  78325. });
  78326. }
  78327. }, function () {
  78328. setTimeout(function () {
  78329. //reconstruct this part of the mesh
  78330. _this.reconstructMesh(submeshIndex);
  78331. successCallback();
  78332. }, 0);
  78333. });
  78334. };
  78335. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  78336. var _this = this;
  78337. this.vertices = [];
  78338. this.triangles = [];
  78339. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78340. var indices = this._mesh.getIndices();
  78341. var submesh = this._mesh.subMeshes[submeshIndex];
  78342. var findInVertices = function (positionToSearch) {
  78343. if (optimizeMesh) {
  78344. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  78345. if (_this.vertices[ii].position.equals(positionToSearch)) {
  78346. return _this.vertices[ii];
  78347. }
  78348. }
  78349. }
  78350. return null;
  78351. };
  78352. var vertexReferences = [];
  78353. var vertexInit = function (i) {
  78354. if (!positionData) {
  78355. return;
  78356. }
  78357. var offset = i + submesh.verticesStart;
  78358. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  78359. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  78360. vertex.originalOffsets.push(offset);
  78361. if (vertex.id === _this.vertices.length) {
  78362. _this.vertices.push(vertex);
  78363. }
  78364. vertexReferences.push(vertex.id);
  78365. };
  78366. //var totalVertices = mesh.getTotalVertices();
  78367. var totalVertices = submesh.verticesCount;
  78368. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  78369. var indicesInit = function (i) {
  78370. if (!indices) {
  78371. return;
  78372. }
  78373. var offset = (submesh.indexStart / 3) + i;
  78374. var pos = (offset * 3);
  78375. var i0 = indices[pos + 0];
  78376. var i1 = indices[pos + 1];
  78377. var i2 = indices[pos + 2];
  78378. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  78379. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  78380. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  78381. var triangle = new DecimationTriangle([v0, v1, v2]);
  78382. triangle.originalOffset = pos;
  78383. _this.triangles.push(triangle);
  78384. };
  78385. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  78386. _this.init(callback);
  78387. });
  78388. });
  78389. };
  78390. QuadraticErrorSimplification.prototype.init = function (callback) {
  78391. var _this = this;
  78392. var triangleInit1 = function (i) {
  78393. var t = _this.triangles[i];
  78394. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  78395. for (var j = 0; j < 3; j++) {
  78396. 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))));
  78397. }
  78398. };
  78399. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  78400. var triangleInit2 = function (i) {
  78401. var t = _this.triangles[i];
  78402. for (var j = 0; j < 3; ++j) {
  78403. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  78404. }
  78405. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78406. };
  78407. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  78408. callback();
  78409. });
  78410. });
  78411. };
  78412. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  78413. var newTriangles = [];
  78414. var i;
  78415. for (i = 0; i < this.vertices.length; ++i) {
  78416. this.vertices[i].triangleCount = 0;
  78417. }
  78418. var t;
  78419. var j;
  78420. for (i = 0; i < this.triangles.length; ++i) {
  78421. if (!this.triangles[i].deleted) {
  78422. t = this.triangles[i];
  78423. for (j = 0; j < 3; ++j) {
  78424. t.vertices[j].triangleCount = 1;
  78425. }
  78426. newTriangles.push(t);
  78427. }
  78428. }
  78429. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  78430. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  78431. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  78432. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  78433. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  78434. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  78435. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  78436. var vertexCount = 0;
  78437. for (i = 0; i < this.vertices.length; ++i) {
  78438. var vertex = this.vertices[i];
  78439. vertex.id = vertexCount;
  78440. if (vertex.triangleCount) {
  78441. vertex.originalOffsets.forEach(function (originalOffset) {
  78442. if (!normalData) {
  78443. return;
  78444. }
  78445. newPositionData.push(vertex.position.x);
  78446. newPositionData.push(vertex.position.y);
  78447. newPositionData.push(vertex.position.z);
  78448. newNormalData.push(normalData[originalOffset * 3]);
  78449. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  78450. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  78451. if (uvs && uvs.length) {
  78452. newUVsData.push(uvs[(originalOffset * 2)]);
  78453. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  78454. }
  78455. else if (colorsData && colorsData.length) {
  78456. newColorsData.push(colorsData[(originalOffset * 4)]);
  78457. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  78458. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  78459. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  78460. }
  78461. ++vertexCount;
  78462. });
  78463. }
  78464. }
  78465. var startingIndex = this._reconstructedMesh.getTotalIndices();
  78466. var startingVertex = this._reconstructedMesh.getTotalVertices();
  78467. var submeshesArray = this._reconstructedMesh.subMeshes;
  78468. this._reconstructedMesh.subMeshes = [];
  78469. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  78470. var originalIndices = this._mesh.getIndices();
  78471. for (i = 0; i < newTriangles.length; ++i) {
  78472. t = newTriangles[i]; //now get the new referencing point for each vertex
  78473. [0, 1, 2].forEach(function (idx) {
  78474. var id = originalIndices[t.originalOffset + idx];
  78475. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  78476. if (offset < 0)
  78477. offset = 0;
  78478. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  78479. });
  78480. }
  78481. //overwriting the old vertex buffers and indices.
  78482. this._reconstructedMesh.setIndices(newIndicesArray);
  78483. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  78484. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  78485. if (newUVsData.length > 0)
  78486. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  78487. if (newColorsData.length > 0)
  78488. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  78489. //create submesh
  78490. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  78491. if (submeshIndex > 0) {
  78492. this._reconstructedMesh.subMeshes = [];
  78493. submeshesArray.forEach(function (submesh) {
  78494. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  78495. });
  78496. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  78497. }
  78498. };
  78499. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  78500. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  78501. this._reconstructedMesh.material = this._mesh.material;
  78502. this._reconstructedMesh.parent = this._mesh.parent;
  78503. this._reconstructedMesh.isVisible = false;
  78504. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  78505. };
  78506. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  78507. for (var i = 0; i < vertex1.triangleCount; ++i) {
  78508. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  78509. if (t.deleted)
  78510. continue;
  78511. var s = this.references[vertex1.triangleStart + i].vertexId;
  78512. var v1 = t.vertices[(s + 1) % 3];
  78513. var v2 = t.vertices[(s + 2) % 3];
  78514. if ((v1 === vertex2 || v2 === vertex2)) {
  78515. deletedArray[i] = true;
  78516. delTr.push(t);
  78517. continue;
  78518. }
  78519. var d1 = v1.position.subtract(point);
  78520. d1 = d1.normalize();
  78521. var d2 = v2.position.subtract(point);
  78522. d2 = d2.normalize();
  78523. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  78524. return true;
  78525. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  78526. deletedArray[i] = false;
  78527. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  78528. return true;
  78529. }
  78530. return false;
  78531. };
  78532. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  78533. var newDeleted = deletedTriangles;
  78534. for (var i = 0; i < vertex.triangleCount; ++i) {
  78535. var ref = this.references[vertex.triangleStart + i];
  78536. var t = this.triangles[ref.triangleId];
  78537. if (t.deleted)
  78538. continue;
  78539. if (deletedArray[i] && t.deletePending) {
  78540. t.deleted = true;
  78541. newDeleted++;
  78542. continue;
  78543. }
  78544. t.vertices[ref.vertexId] = origVertex;
  78545. t.isDirty = true;
  78546. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  78547. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  78548. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  78549. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  78550. this.references.push(ref);
  78551. }
  78552. return newDeleted;
  78553. };
  78554. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  78555. for (var i = 0; i < this.vertices.length; ++i) {
  78556. var vCount = [];
  78557. var vId = [];
  78558. var v = this.vertices[i];
  78559. var j;
  78560. for (j = 0; j < v.triangleCount; ++j) {
  78561. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  78562. for (var ii = 0; ii < 3; ii++) {
  78563. var ofs = 0;
  78564. var vv = triangle.vertices[ii];
  78565. while (ofs < vCount.length) {
  78566. if (vId[ofs] === vv.id)
  78567. break;
  78568. ++ofs;
  78569. }
  78570. if (ofs === vCount.length) {
  78571. vCount.push(1);
  78572. vId.push(vv.id);
  78573. }
  78574. else {
  78575. vCount[ofs]++;
  78576. }
  78577. }
  78578. }
  78579. for (j = 0; j < vCount.length; ++j) {
  78580. if (vCount[j] === 1) {
  78581. this.vertices[vId[j]].isBorder = true;
  78582. }
  78583. else {
  78584. this.vertices[vId[j]].isBorder = false;
  78585. }
  78586. }
  78587. }
  78588. };
  78589. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  78590. if (identifyBorders === void 0) { identifyBorders = false; }
  78591. var i;
  78592. if (!identifyBorders) {
  78593. var newTrianglesVector = [];
  78594. for (i = 0; i < this.triangles.length; ++i) {
  78595. if (!this.triangles[i].deleted) {
  78596. newTrianglesVector.push(this.triangles[i]);
  78597. }
  78598. }
  78599. this.triangles = newTrianglesVector;
  78600. }
  78601. for (i = 0; i < this.vertices.length; ++i) {
  78602. this.vertices[i].triangleCount = 0;
  78603. this.vertices[i].triangleStart = 0;
  78604. }
  78605. var t;
  78606. var j;
  78607. var v;
  78608. for (i = 0; i < this.triangles.length; ++i) {
  78609. t = this.triangles[i];
  78610. for (j = 0; j < 3; ++j) {
  78611. v = t.vertices[j];
  78612. v.triangleCount++;
  78613. }
  78614. }
  78615. var tStart = 0;
  78616. for (i = 0; i < this.vertices.length; ++i) {
  78617. this.vertices[i].triangleStart = tStart;
  78618. tStart += this.vertices[i].triangleCount;
  78619. this.vertices[i].triangleCount = 0;
  78620. }
  78621. var newReferences = new Array(this.triangles.length * 3);
  78622. for (i = 0; i < this.triangles.length; ++i) {
  78623. t = this.triangles[i];
  78624. for (j = 0; j < 3; ++j) {
  78625. v = t.vertices[j];
  78626. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  78627. v.triangleCount++;
  78628. }
  78629. }
  78630. this.references = newReferences;
  78631. if (identifyBorders) {
  78632. this.identifyBorder();
  78633. }
  78634. };
  78635. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  78636. var x = point.x;
  78637. var y = point.y;
  78638. var z = point.z;
  78639. 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
  78640. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  78641. };
  78642. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  78643. var q = vertex1.q.add(vertex2.q);
  78644. var border = vertex1.isBorder && vertex2.isBorder;
  78645. var error = 0;
  78646. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  78647. if (qDet !== 0 && !border) {
  78648. if (!pointResult) {
  78649. pointResult = BABYLON.Vector3.Zero();
  78650. }
  78651. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  78652. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  78653. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  78654. error = this.vertexError(q, pointResult);
  78655. }
  78656. else {
  78657. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  78658. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  78659. var error1 = this.vertexError(q, vertex1.position);
  78660. var error2 = this.vertexError(q, vertex2.position);
  78661. var error3 = this.vertexError(q, p3);
  78662. error = Math.min(error1, error2, error3);
  78663. if (error === error1) {
  78664. if (pointResult) {
  78665. pointResult.copyFrom(vertex1.position);
  78666. }
  78667. }
  78668. else if (error === error2) {
  78669. if (pointResult) {
  78670. pointResult.copyFrom(vertex2.position);
  78671. }
  78672. }
  78673. else {
  78674. if (pointResult) {
  78675. pointResult.copyFrom(p3);
  78676. }
  78677. }
  78678. }
  78679. return error;
  78680. };
  78681. return QuadraticErrorSimplification;
  78682. }());
  78683. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  78684. })(BABYLON || (BABYLON = {}));
  78685. //# sourceMappingURL=babylon.meshSimplification.js.map
  78686. var BABYLON;
  78687. (function (BABYLON) {
  78688. var MeshLODLevel = /** @class */ (function () {
  78689. function MeshLODLevel(distance, mesh) {
  78690. this.distance = distance;
  78691. this.mesh = mesh;
  78692. }
  78693. return MeshLODLevel;
  78694. }());
  78695. BABYLON.MeshLODLevel = MeshLODLevel;
  78696. })(BABYLON || (BABYLON = {}));
  78697. //# sourceMappingURL=babylon.meshLODLevel.js.map
  78698. var BABYLON;
  78699. (function (BABYLON) {
  78700. /**
  78701. * Defines the root class used to create scene optimization to use with SceneOptimizer
  78702. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78703. */
  78704. var SceneOptimization = /** @class */ (function () {
  78705. /**
  78706. * Creates the SceneOptimization object
  78707. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78708. * @param desc defines the description associated with the optimization
  78709. */
  78710. function SceneOptimization(
  78711. /**
  78712. * Defines the priority of this optimization (0 by default which means first in the list)
  78713. */
  78714. priority) {
  78715. if (priority === void 0) { priority = 0; }
  78716. this.priority = priority;
  78717. }
  78718. /**
  78719. * Gets a string describing the action executed by the current optimization
  78720. * @returns description string
  78721. */
  78722. SceneOptimization.prototype.getDescription = function () {
  78723. return "";
  78724. };
  78725. /**
  78726. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78727. * @param scene defines the current scene where to apply this optimization
  78728. * @param optimizer defines the current optimizer
  78729. * @returns true if everything that can be done was applied
  78730. */
  78731. SceneOptimization.prototype.apply = function (scene, optimizer) {
  78732. return true;
  78733. };
  78734. ;
  78735. return SceneOptimization;
  78736. }());
  78737. BABYLON.SceneOptimization = SceneOptimization;
  78738. /**
  78739. * Defines an optimization used to reduce the size of render target textures
  78740. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78741. */
  78742. var TextureOptimization = /** @class */ (function (_super) {
  78743. __extends(TextureOptimization, _super);
  78744. /**
  78745. * Creates the TextureOptimization object
  78746. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78747. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  78748. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  78749. */
  78750. function TextureOptimization(
  78751. /**
  78752. * Defines the priority of this optimization (0 by default which means first in the list)
  78753. */
  78754. priority,
  78755. /**
  78756. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  78757. */
  78758. maximumSize,
  78759. /**
  78760. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  78761. */
  78762. step) {
  78763. if (priority === void 0) { priority = 0; }
  78764. if (maximumSize === void 0) { maximumSize = 1024; }
  78765. if (step === void 0) { step = 0.5; }
  78766. var _this = _super.call(this, priority) || this;
  78767. _this.priority = priority;
  78768. _this.maximumSize = maximumSize;
  78769. _this.step = step;
  78770. return _this;
  78771. }
  78772. /**
  78773. * Gets a string describing the action executed by the current optimization
  78774. * @returns description string
  78775. */
  78776. TextureOptimization.prototype.getDescription = function () {
  78777. return "Reducing render target texture size to " + this.maximumSize;
  78778. };
  78779. /**
  78780. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78781. * @param scene defines the current scene where to apply this optimization
  78782. * @param optimizer defines the current optimizer
  78783. * @returns true if everything that can be done was applied
  78784. */
  78785. TextureOptimization.prototype.apply = function (scene, optimizer) {
  78786. var allDone = true;
  78787. for (var index = 0; index < scene.textures.length; index++) {
  78788. var texture = scene.textures[index];
  78789. if (!texture.canRescale || texture.getContext) {
  78790. continue;
  78791. }
  78792. var currentSize = texture.getSize();
  78793. var maxDimension = Math.max(currentSize.width, currentSize.height);
  78794. if (maxDimension > this.maximumSize) {
  78795. texture.scale(this.step);
  78796. allDone = false;
  78797. }
  78798. }
  78799. return allDone;
  78800. };
  78801. return TextureOptimization;
  78802. }(SceneOptimization));
  78803. BABYLON.TextureOptimization = TextureOptimization;
  78804. /**
  78805. * Defines an optimization used to increase or decrease the rendering resolution
  78806. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78807. */
  78808. var HardwareScalingOptimization = /** @class */ (function (_super) {
  78809. __extends(HardwareScalingOptimization, _super);
  78810. /**
  78811. * Creates the HardwareScalingOptimization object
  78812. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78813. * @param maximumScale defines the maximum scale to use (2 by default)
  78814. * @param step defines the step to use between two passes (0.5 by default)
  78815. */
  78816. function HardwareScalingOptimization(
  78817. /**
  78818. * Defines the priority of this optimization (0 by default which means first in the list)
  78819. */
  78820. priority,
  78821. /**
  78822. * Defines the maximum scale to use (2 by default)
  78823. */
  78824. maximumScale,
  78825. /**
  78826. * Defines the step to use between two passes (0.5 by default)
  78827. */
  78828. step) {
  78829. if (priority === void 0) { priority = 0; }
  78830. if (maximumScale === void 0) { maximumScale = 2; }
  78831. if (step === void 0) { step = 0.25; }
  78832. var _this = _super.call(this, priority) || this;
  78833. _this.priority = priority;
  78834. _this.maximumScale = maximumScale;
  78835. _this.step = step;
  78836. _this._currentScale = -1;
  78837. _this._directionOffset = 1;
  78838. return _this;
  78839. }
  78840. /**
  78841. * Gets a string describing the action executed by the current optimization
  78842. * @return description string
  78843. */
  78844. HardwareScalingOptimization.prototype.getDescription = function () {
  78845. return "Setting hardware scaling level to " + this._currentScale;
  78846. };
  78847. /**
  78848. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78849. * @param scene defines the current scene where to apply this optimization
  78850. * @param optimizer defines the current optimizer
  78851. * @returns true if everything that can be done was applied
  78852. */
  78853. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  78854. if (this._currentScale === -1) {
  78855. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  78856. if (this._currentScale > this.maximumScale) {
  78857. this._directionOffset = -1;
  78858. }
  78859. }
  78860. this._currentScale += this._directionOffset * this.step;
  78861. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  78862. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  78863. };
  78864. ;
  78865. return HardwareScalingOptimization;
  78866. }(SceneOptimization));
  78867. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  78868. /**
  78869. * Defines an optimization used to remove shadows
  78870. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78871. */
  78872. var ShadowsOptimization = /** @class */ (function (_super) {
  78873. __extends(ShadowsOptimization, _super);
  78874. function ShadowsOptimization() {
  78875. return _super !== null && _super.apply(this, arguments) || this;
  78876. }
  78877. /**
  78878. * Gets a string describing the action executed by the current optimization
  78879. * @return description string
  78880. */
  78881. ShadowsOptimization.prototype.getDescription = function () {
  78882. return "Turning shadows on/off";
  78883. };
  78884. /**
  78885. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78886. * @param scene defines the current scene where to apply this optimization
  78887. * @param optimizer defines the current optimizer
  78888. * @returns true if everything that can be done was applied
  78889. */
  78890. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  78891. scene.shadowsEnabled = optimizer.isInImprovementMode;
  78892. return true;
  78893. };
  78894. ;
  78895. return ShadowsOptimization;
  78896. }(SceneOptimization));
  78897. BABYLON.ShadowsOptimization = ShadowsOptimization;
  78898. /**
  78899. * Defines an optimization used to turn post-processes off
  78900. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78901. */
  78902. var PostProcessesOptimization = /** @class */ (function (_super) {
  78903. __extends(PostProcessesOptimization, _super);
  78904. function PostProcessesOptimization() {
  78905. return _super !== null && _super.apply(this, arguments) || this;
  78906. }
  78907. /**
  78908. * Gets a string describing the action executed by the current optimization
  78909. * @return description string
  78910. */
  78911. PostProcessesOptimization.prototype.getDescription = function () {
  78912. return "Turning post-processes on/off";
  78913. };
  78914. /**
  78915. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78916. * @param scene defines the current scene where to apply this optimization
  78917. * @param optimizer defines the current optimizer
  78918. * @returns true if everything that can be done was applied
  78919. */
  78920. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  78921. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  78922. return true;
  78923. };
  78924. ;
  78925. return PostProcessesOptimization;
  78926. }(SceneOptimization));
  78927. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  78928. /**
  78929. * Defines an optimization used to turn lens flares off
  78930. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78931. */
  78932. var LensFlaresOptimization = /** @class */ (function (_super) {
  78933. __extends(LensFlaresOptimization, _super);
  78934. function LensFlaresOptimization() {
  78935. return _super !== null && _super.apply(this, arguments) || this;
  78936. }
  78937. /**
  78938. * Gets a string describing the action executed by the current optimization
  78939. * @return description string
  78940. */
  78941. LensFlaresOptimization.prototype.getDescription = function () {
  78942. return "Turning lens flares on/off";
  78943. };
  78944. /**
  78945. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78946. * @param scene defines the current scene where to apply this optimization
  78947. * @param optimizer defines the current optimizer
  78948. * @returns true if everything that can be done was applied
  78949. */
  78950. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  78951. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  78952. return true;
  78953. };
  78954. ;
  78955. return LensFlaresOptimization;
  78956. }(SceneOptimization));
  78957. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  78958. /**
  78959. * Defines an optimization based on user defined callback.
  78960. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78961. */
  78962. var CustomOptimization = /** @class */ (function (_super) {
  78963. __extends(CustomOptimization, _super);
  78964. function CustomOptimization() {
  78965. return _super !== null && _super.apply(this, arguments) || this;
  78966. }
  78967. /**
  78968. * Gets a string describing the action executed by the current optimization
  78969. * @returns description string
  78970. */
  78971. CustomOptimization.prototype.getDescription = function () {
  78972. if (this.onGetDescription) {
  78973. return this.onGetDescription();
  78974. }
  78975. return "Running user defined callback";
  78976. };
  78977. /**
  78978. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78979. * @param scene defines the current scene where to apply this optimization
  78980. * @param optimizer defines the current optimizer
  78981. * @returns true if everything that can be done was applied
  78982. */
  78983. CustomOptimization.prototype.apply = function (scene, optimizer) {
  78984. if (this.onApply) {
  78985. return this.onApply(scene, optimizer);
  78986. }
  78987. return true;
  78988. };
  78989. ;
  78990. return CustomOptimization;
  78991. }(SceneOptimization));
  78992. BABYLON.CustomOptimization = CustomOptimization;
  78993. /**
  78994. * Defines an optimization used to turn particles off
  78995. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78996. */
  78997. var ParticlesOptimization = /** @class */ (function (_super) {
  78998. __extends(ParticlesOptimization, _super);
  78999. function ParticlesOptimization() {
  79000. return _super !== null && _super.apply(this, arguments) || this;
  79001. }
  79002. /**
  79003. * Gets a string describing the action executed by the current optimization
  79004. * @return description string
  79005. */
  79006. ParticlesOptimization.prototype.getDescription = function () {
  79007. return "Turning particles on/off";
  79008. };
  79009. /**
  79010. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79011. * @param scene defines the current scene where to apply this optimization
  79012. * @param optimizer defines the current optimizer
  79013. * @returns true if everything that can be done was applied
  79014. */
  79015. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  79016. scene.particlesEnabled = optimizer.isInImprovementMode;
  79017. return true;
  79018. };
  79019. ;
  79020. return ParticlesOptimization;
  79021. }(SceneOptimization));
  79022. BABYLON.ParticlesOptimization = ParticlesOptimization;
  79023. /**
  79024. * Defines an optimization used to turn render targets off
  79025. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79026. */
  79027. var RenderTargetsOptimization = /** @class */ (function (_super) {
  79028. __extends(RenderTargetsOptimization, _super);
  79029. function RenderTargetsOptimization() {
  79030. return _super !== null && _super.apply(this, arguments) || this;
  79031. }
  79032. /**
  79033. * Gets a string describing the action executed by the current optimization
  79034. * @return description string
  79035. */
  79036. RenderTargetsOptimization.prototype.getDescription = function () {
  79037. return "Turning render targets off";
  79038. };
  79039. /**
  79040. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79041. * @param scene defines the current scene where to apply this optimization
  79042. * @param optimizer defines the current optimizer
  79043. * @returns true if everything that can be done was applied
  79044. */
  79045. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  79046. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  79047. return true;
  79048. };
  79049. ;
  79050. return RenderTargetsOptimization;
  79051. }(SceneOptimization));
  79052. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  79053. /**
  79054. * Defines an optimization used to merge meshes with compatible materials
  79055. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79056. */
  79057. var MergeMeshesOptimization = /** @class */ (function (_super) {
  79058. __extends(MergeMeshesOptimization, _super);
  79059. function MergeMeshesOptimization() {
  79060. var _this = _super !== null && _super.apply(this, arguments) || this;
  79061. _this._canBeMerged = function (abstractMesh) {
  79062. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  79063. return false;
  79064. }
  79065. var mesh = abstractMesh;
  79066. if (!mesh.isVisible || !mesh.isEnabled()) {
  79067. return false;
  79068. }
  79069. if (mesh.instances.length > 0) {
  79070. return false;
  79071. }
  79072. if (mesh.skeleton || mesh.hasLODLevels) {
  79073. return false;
  79074. }
  79075. if (mesh.parent) {
  79076. return false;
  79077. }
  79078. return true;
  79079. };
  79080. return _this;
  79081. }
  79082. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  79083. /**
  79084. * Gets or sets a boolean which defines if optimization octree has to be updated
  79085. */
  79086. get: function () {
  79087. return MergeMeshesOptimization._UpdateSelectionTree;
  79088. },
  79089. /**
  79090. * Gets or sets a boolean which defines if optimization octree has to be updated
  79091. */
  79092. set: function (value) {
  79093. MergeMeshesOptimization._UpdateSelectionTree = value;
  79094. },
  79095. enumerable: true,
  79096. configurable: true
  79097. });
  79098. /**
  79099. * Gets a string describing the action executed by the current optimization
  79100. * @return description string
  79101. */
  79102. MergeMeshesOptimization.prototype.getDescription = function () {
  79103. return "Merging similar meshes together";
  79104. };
  79105. /**
  79106. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  79107. * @param scene defines the current scene where to apply this optimization
  79108. * @param optimizer defines the current optimizer
  79109. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  79110. * @returns true if everything that can be done was applied
  79111. */
  79112. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  79113. var globalPool = scene.meshes.slice(0);
  79114. var globalLength = globalPool.length;
  79115. for (var index = 0; index < globalLength; index++) {
  79116. var currentPool = new Array();
  79117. var current = globalPool[index];
  79118. // Checks
  79119. if (!this._canBeMerged(current)) {
  79120. continue;
  79121. }
  79122. currentPool.push(current);
  79123. // Find compatible meshes
  79124. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  79125. var otherMesh = globalPool[subIndex];
  79126. if (!this._canBeMerged(otherMesh)) {
  79127. continue;
  79128. }
  79129. if (otherMesh.material !== current.material) {
  79130. continue;
  79131. }
  79132. if (otherMesh.checkCollisions !== current.checkCollisions) {
  79133. continue;
  79134. }
  79135. currentPool.push(otherMesh);
  79136. globalLength--;
  79137. globalPool.splice(subIndex, 1);
  79138. subIndex--;
  79139. }
  79140. if (currentPool.length < 2) {
  79141. continue;
  79142. }
  79143. // Merge meshes
  79144. BABYLON.Mesh.MergeMeshes(currentPool);
  79145. }
  79146. if (updateSelectionTree != undefined) {
  79147. if (updateSelectionTree) {
  79148. scene.createOrUpdateSelectionOctree();
  79149. }
  79150. }
  79151. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  79152. scene.createOrUpdateSelectionOctree();
  79153. }
  79154. return true;
  79155. };
  79156. ;
  79157. MergeMeshesOptimization._UpdateSelectionTree = false;
  79158. return MergeMeshesOptimization;
  79159. }(SceneOptimization));
  79160. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  79161. /**
  79162. * Defines a list of options used by SceneOptimizer
  79163. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79164. */
  79165. var SceneOptimizerOptions = /** @class */ (function () {
  79166. /**
  79167. * Creates a new list of options used by SceneOptimizer
  79168. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  79169. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  79170. */
  79171. function SceneOptimizerOptions(
  79172. /**
  79173. * Defines the target frame rate to reach (60 by default)
  79174. */
  79175. targetFrameRate,
  79176. /**
  79177. * Defines the interval between two checkes (2000ms by default)
  79178. */
  79179. trackerDuration) {
  79180. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  79181. if (trackerDuration === void 0) { trackerDuration = 2000; }
  79182. this.targetFrameRate = targetFrameRate;
  79183. this.trackerDuration = trackerDuration;
  79184. /**
  79185. * Gets the list of optimizations to apply
  79186. */
  79187. this.optimizations = new Array();
  79188. }
  79189. /**
  79190. * Add a new optimization
  79191. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  79192. * @returns the current SceneOptimizerOptions
  79193. */
  79194. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  79195. this.optimizations.push(optimization);
  79196. return this;
  79197. };
  79198. /**
  79199. * Add a new custom optimization
  79200. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  79201. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  79202. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  79203. * @returns the current SceneOptimizerOptions
  79204. */
  79205. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  79206. if (priority === void 0) { priority = 0; }
  79207. var optimization = new CustomOptimization(priority);
  79208. optimization.onApply = onApply;
  79209. optimization.onGetDescription = onGetDescription;
  79210. this.optimizations.push(optimization);
  79211. return this;
  79212. };
  79213. /**
  79214. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  79215. * @param targetFrameRate defines the target frame rate (60 by default)
  79216. * @returns a SceneOptimizerOptions object
  79217. */
  79218. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  79219. var result = new SceneOptimizerOptions(targetFrameRate);
  79220. var priority = 0;
  79221. result.addOptimization(new MergeMeshesOptimization(priority));
  79222. result.addOptimization(new ShadowsOptimization(priority));
  79223. result.addOptimization(new LensFlaresOptimization(priority));
  79224. // Next priority
  79225. priority++;
  79226. result.addOptimization(new PostProcessesOptimization(priority));
  79227. result.addOptimization(new ParticlesOptimization(priority));
  79228. // Next priority
  79229. priority++;
  79230. result.addOptimization(new TextureOptimization(priority, 1024));
  79231. return result;
  79232. };
  79233. /**
  79234. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  79235. * @param targetFrameRate defines the target frame rate (60 by default)
  79236. * @returns a SceneOptimizerOptions object
  79237. */
  79238. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  79239. var result = new SceneOptimizerOptions(targetFrameRate);
  79240. var priority = 0;
  79241. result.addOptimization(new MergeMeshesOptimization(priority));
  79242. result.addOptimization(new ShadowsOptimization(priority));
  79243. result.addOptimization(new LensFlaresOptimization(priority));
  79244. // Next priority
  79245. priority++;
  79246. result.addOptimization(new PostProcessesOptimization(priority));
  79247. result.addOptimization(new ParticlesOptimization(priority));
  79248. // Next priority
  79249. priority++;
  79250. result.addOptimization(new TextureOptimization(priority, 512));
  79251. // Next priority
  79252. priority++;
  79253. result.addOptimization(new RenderTargetsOptimization(priority));
  79254. // Next priority
  79255. priority++;
  79256. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  79257. return result;
  79258. };
  79259. /**
  79260. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  79261. * @param targetFrameRate defines the target frame rate (60 by default)
  79262. * @returns a SceneOptimizerOptions object
  79263. */
  79264. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  79265. var result = new SceneOptimizerOptions(targetFrameRate);
  79266. var priority = 0;
  79267. result.addOptimization(new MergeMeshesOptimization(priority));
  79268. result.addOptimization(new ShadowsOptimization(priority));
  79269. result.addOptimization(new LensFlaresOptimization(priority));
  79270. // Next priority
  79271. priority++;
  79272. result.addOptimization(new PostProcessesOptimization(priority));
  79273. result.addOptimization(new ParticlesOptimization(priority));
  79274. // Next priority
  79275. priority++;
  79276. result.addOptimization(new TextureOptimization(priority, 256));
  79277. // Next priority
  79278. priority++;
  79279. result.addOptimization(new RenderTargetsOptimization(priority));
  79280. // Next priority
  79281. priority++;
  79282. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  79283. return result;
  79284. };
  79285. return SceneOptimizerOptions;
  79286. }());
  79287. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  79288. /**
  79289. * Class used to run optimizations in order to reach a target frame rate
  79290. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  79291. */
  79292. var SceneOptimizer = /** @class */ (function () {
  79293. /**
  79294. * Creates a new SceneOptimizer
  79295. * @param scene defines the scene to work on
  79296. * @param options defines the options to use with the SceneOptimizer
  79297. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  79298. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  79299. */
  79300. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  79301. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  79302. if (improvementMode === void 0) { improvementMode = false; }
  79303. var _this = this;
  79304. this._isRunning = false;
  79305. this._currentPriorityLevel = 0;
  79306. this._targetFrameRate = 60;
  79307. this._trackerDuration = 2000;
  79308. this._currentFrameRate = 0;
  79309. this._improvementMode = false;
  79310. /**
  79311. * Defines an observable called when the optimizer reaches the target frame rate
  79312. */
  79313. this.onSuccessObservable = new BABYLON.Observable();
  79314. /**
  79315. * Defines an observable called when the optimizer enables an optimization
  79316. */
  79317. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  79318. /**
  79319. * Defines an observable called when the optimizer is not able to reach the target frame rate
  79320. */
  79321. this.onFailureObservable = new BABYLON.Observable();
  79322. if (!options) {
  79323. this._options = new SceneOptimizerOptions();
  79324. }
  79325. else {
  79326. this._options = options;
  79327. }
  79328. if (this._options.targetFrameRate) {
  79329. this._targetFrameRate = this._options.targetFrameRate;
  79330. }
  79331. if (this._options.trackerDuration) {
  79332. this._trackerDuration = this._options.trackerDuration;
  79333. }
  79334. if (autoGeneratePriorities) {
  79335. var priority = 0;
  79336. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  79337. var optim = _a[_i];
  79338. optim.priority = priority++;
  79339. }
  79340. }
  79341. this._improvementMode = improvementMode;
  79342. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79343. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  79344. _this._sceneDisposeObserver = null;
  79345. _this.dispose();
  79346. });
  79347. }
  79348. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  79349. /**
  79350. * Gets a boolean indicating if the optimizer is in improvement mode
  79351. */
  79352. get: function () {
  79353. return this._improvementMode;
  79354. },
  79355. enumerable: true,
  79356. configurable: true
  79357. });
  79358. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  79359. /**
  79360. * Gets the current priority level (0 at start)
  79361. */
  79362. get: function () {
  79363. return this._currentPriorityLevel;
  79364. },
  79365. enumerable: true,
  79366. configurable: true
  79367. });
  79368. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  79369. /**
  79370. * Gets the current frame rate checked by the SceneOptimizer
  79371. */
  79372. get: function () {
  79373. return this._currentFrameRate;
  79374. },
  79375. enumerable: true,
  79376. configurable: true
  79377. });
  79378. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  79379. /**
  79380. * Gets or sets the current target frame rate (60 by default)
  79381. */
  79382. get: function () {
  79383. return this._targetFrameRate;
  79384. },
  79385. /**
  79386. * Gets or sets the current target frame rate (60 by default)
  79387. */
  79388. set: function (value) {
  79389. this._targetFrameRate = value;
  79390. },
  79391. enumerable: true,
  79392. configurable: true
  79393. });
  79394. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  79395. /**
  79396. * Gets or sets the current interval between two checks (every 2000ms by default)
  79397. */
  79398. get: function () {
  79399. return this._trackerDuration;
  79400. },
  79401. /**
  79402. * Gets or sets the current interval between two checks (every 2000ms by default)
  79403. */
  79404. set: function (value) {
  79405. this._trackerDuration = value;
  79406. },
  79407. enumerable: true,
  79408. configurable: true
  79409. });
  79410. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  79411. /**
  79412. * Gets the list of active optimizations
  79413. */
  79414. get: function () {
  79415. return this._options.optimizations;
  79416. },
  79417. enumerable: true,
  79418. configurable: true
  79419. });
  79420. /**
  79421. * Stops the current optimizer
  79422. */
  79423. SceneOptimizer.prototype.stop = function () {
  79424. this._isRunning = false;
  79425. };
  79426. /**
  79427. * Reset the optimizer to initial step (current priority level = 0)
  79428. */
  79429. SceneOptimizer.prototype.reset = function () {
  79430. this._currentPriorityLevel = 0;
  79431. };
  79432. /**
  79433. * Start the optimizer. By default it will try to reach a specific framerate
  79434. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  79435. */
  79436. SceneOptimizer.prototype.start = function () {
  79437. var _this = this;
  79438. if (this._isRunning) {
  79439. return;
  79440. }
  79441. this._isRunning = true;
  79442. // Let's wait for the scene to be ready before running our check
  79443. this._scene.executeWhenReady(function () {
  79444. setTimeout(function () {
  79445. _this._checkCurrentState();
  79446. }, _this._trackerDuration);
  79447. });
  79448. };
  79449. SceneOptimizer.prototype._checkCurrentState = function () {
  79450. var _this = this;
  79451. if (!this._isRunning) {
  79452. return;
  79453. }
  79454. var scene = this._scene;
  79455. var options = this._options;
  79456. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  79457. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  79458. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  79459. this._isRunning = false;
  79460. this.onSuccessObservable.notifyObservers(this);
  79461. return;
  79462. }
  79463. // Apply current level of optimizations
  79464. var allDone = true;
  79465. var noOptimizationApplied = true;
  79466. for (var index = 0; index < options.optimizations.length; index++) {
  79467. var optimization = options.optimizations[index];
  79468. if (optimization.priority === this._currentPriorityLevel) {
  79469. noOptimizationApplied = false;
  79470. allDone = allDone && optimization.apply(scene, this);
  79471. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  79472. }
  79473. }
  79474. // If no optimization was applied, this is a failure :(
  79475. if (noOptimizationApplied) {
  79476. this._isRunning = false;
  79477. this.onFailureObservable.notifyObservers(this);
  79478. return;
  79479. }
  79480. // If all optimizations were done, move to next level
  79481. if (allDone) {
  79482. this._currentPriorityLevel++;
  79483. }
  79484. // Let's the system running for a specific amount of time before checking FPS
  79485. scene.executeWhenReady(function () {
  79486. setTimeout(function () {
  79487. _this._checkCurrentState();
  79488. }, _this._trackerDuration);
  79489. });
  79490. };
  79491. /**
  79492. * Release all resources
  79493. */
  79494. SceneOptimizer.prototype.dispose = function () {
  79495. this.stop();
  79496. this.onSuccessObservable.clear();
  79497. this.onFailureObservable.clear();
  79498. this.onNewOptimizationAppliedObservable.clear();
  79499. if (this._sceneDisposeObserver) {
  79500. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  79501. }
  79502. };
  79503. /**
  79504. * Helper function to create a SceneOptimizer with one single line of code
  79505. * @param scene defines the scene to work on
  79506. * @param options defines the options to use with the SceneOptimizer
  79507. * @param onSuccess defines a callback to call on success
  79508. * @param onFailure defines a callback to call on failure
  79509. * @returns the new SceneOptimizer object
  79510. */
  79511. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  79512. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  79513. if (onSuccess) {
  79514. optimizer.onSuccessObservable.add(function () {
  79515. onSuccess();
  79516. });
  79517. }
  79518. if (onFailure) {
  79519. optimizer.onFailureObservable.add(function () {
  79520. onFailure();
  79521. });
  79522. }
  79523. optimizer.start();
  79524. return optimizer;
  79525. };
  79526. return SceneOptimizer;
  79527. }());
  79528. BABYLON.SceneOptimizer = SceneOptimizer;
  79529. })(BABYLON || (BABYLON = {}));
  79530. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  79531. var BABYLON;
  79532. (function (BABYLON) {
  79533. var OutlineRenderer = /** @class */ (function () {
  79534. function OutlineRenderer(scene) {
  79535. this.zOffset = 1;
  79536. this._scene = scene;
  79537. }
  79538. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  79539. var _this = this;
  79540. if (useOverlay === void 0) { useOverlay = false; }
  79541. var scene = this._scene;
  79542. var engine = this._scene.getEngine();
  79543. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79544. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  79545. return;
  79546. }
  79547. var mesh = subMesh.getRenderingMesh();
  79548. var material = subMesh.getMaterial();
  79549. if (!material || !scene.activeCamera) {
  79550. return;
  79551. }
  79552. engine.enableEffect(this._effect);
  79553. // Logarithmic depth
  79554. if (material.useLogarithmicDepth) {
  79555. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  79556. }
  79557. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  79558. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  79559. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79560. // Bones
  79561. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79562. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79563. }
  79564. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  79565. // Alpha test
  79566. if (material && material.needAlphaTesting()) {
  79567. var alphaTexture = material.getAlphaTestTexture();
  79568. if (alphaTexture) {
  79569. this._effect.setTexture("diffuseSampler", alphaTexture);
  79570. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79571. }
  79572. }
  79573. engine.setZOffset(-this.zOffset);
  79574. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  79575. engine.setZOffset(0);
  79576. };
  79577. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  79578. var defines = [];
  79579. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79580. var mesh = subMesh.getMesh();
  79581. var material = subMesh.getMaterial();
  79582. if (material) {
  79583. // Alpha test
  79584. if (material.needAlphaTesting()) {
  79585. defines.push("#define ALPHATEST");
  79586. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79587. attribs.push(BABYLON.VertexBuffer.UVKind);
  79588. defines.push("#define UV1");
  79589. }
  79590. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79591. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79592. defines.push("#define UV2");
  79593. }
  79594. }
  79595. //Logarithmic depth
  79596. if (material.useLogarithmicDepth) {
  79597. defines.push("#define LOGARITHMICDEPTH");
  79598. }
  79599. }
  79600. // Bones
  79601. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79602. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79603. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79604. if (mesh.numBoneInfluencers > 4) {
  79605. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79606. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79607. }
  79608. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79609. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79610. }
  79611. else {
  79612. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79613. }
  79614. // Instances
  79615. if (useInstances) {
  79616. defines.push("#define INSTANCES");
  79617. attribs.push("world0");
  79618. attribs.push("world1");
  79619. attribs.push("world2");
  79620. attribs.push("world3");
  79621. }
  79622. // Get correct effect
  79623. var join = defines.join("\n");
  79624. if (this._cachedDefines !== join) {
  79625. this._cachedDefines = join;
  79626. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  79627. }
  79628. return this._effect.isReady();
  79629. };
  79630. return OutlineRenderer;
  79631. }());
  79632. BABYLON.OutlineRenderer = OutlineRenderer;
  79633. })(BABYLON || (BABYLON = {}));
  79634. //# sourceMappingURL=babylon.outlineRenderer.js.map
  79635. var BABYLON;
  79636. (function (BABYLON) {
  79637. var FaceAdjacencies = /** @class */ (function () {
  79638. function FaceAdjacencies() {
  79639. this.edges = new Array();
  79640. this.edgesConnectedCount = 0;
  79641. }
  79642. return FaceAdjacencies;
  79643. }());
  79644. var EdgesRenderer = /** @class */ (function () {
  79645. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  79646. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  79647. if (epsilon === void 0) { epsilon = 0.95; }
  79648. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  79649. this.edgesWidthScalerForOrthographic = 1000.0;
  79650. this.edgesWidthScalerForPerspective = 50.0;
  79651. this._linesPositions = new Array();
  79652. this._linesNormals = new Array();
  79653. this._linesIndices = new Array();
  79654. this._buffers = {};
  79655. this._checkVerticesInsteadOfIndices = false;
  79656. this._source = source;
  79657. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  79658. this._epsilon = epsilon;
  79659. this._prepareRessources();
  79660. this._generateEdgesLines();
  79661. }
  79662. EdgesRenderer.prototype._prepareRessources = function () {
  79663. if (this._lineShader) {
  79664. return;
  79665. }
  79666. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  79667. attributes: ["position", "normal"],
  79668. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  79669. });
  79670. this._lineShader.disableDepthWrite = true;
  79671. this._lineShader.backFaceCulling = false;
  79672. };
  79673. EdgesRenderer.prototype._rebuild = function () {
  79674. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79675. if (buffer) {
  79676. buffer._rebuild();
  79677. }
  79678. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79679. if (buffer) {
  79680. buffer._rebuild();
  79681. }
  79682. var scene = this._source.getScene();
  79683. var engine = scene.getEngine();
  79684. this._ib = engine.createIndexBuffer(this._linesIndices);
  79685. };
  79686. EdgesRenderer.prototype.dispose = function () {
  79687. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79688. if (buffer) {
  79689. buffer.dispose();
  79690. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  79691. }
  79692. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79693. if (buffer) {
  79694. buffer.dispose();
  79695. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  79696. }
  79697. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  79698. this._lineShader.dispose();
  79699. };
  79700. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  79701. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  79702. return 0;
  79703. }
  79704. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  79705. return 1;
  79706. }
  79707. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  79708. return 2;
  79709. }
  79710. return -1;
  79711. };
  79712. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  79713. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  79714. return 0;
  79715. }
  79716. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  79717. return 1;
  79718. }
  79719. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  79720. return 2;
  79721. }
  79722. return -1;
  79723. };
  79724. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  79725. var needToCreateLine;
  79726. if (edge === undefined) {
  79727. needToCreateLine = true;
  79728. }
  79729. else {
  79730. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  79731. needToCreateLine = dotProduct < this._epsilon;
  79732. }
  79733. if (needToCreateLine) {
  79734. var offset = this._linesPositions.length / 3;
  79735. var normal = p0.subtract(p1);
  79736. normal.normalize();
  79737. // Positions
  79738. this._linesPositions.push(p0.x);
  79739. this._linesPositions.push(p0.y);
  79740. this._linesPositions.push(p0.z);
  79741. this._linesPositions.push(p0.x);
  79742. this._linesPositions.push(p0.y);
  79743. this._linesPositions.push(p0.z);
  79744. this._linesPositions.push(p1.x);
  79745. this._linesPositions.push(p1.y);
  79746. this._linesPositions.push(p1.z);
  79747. this._linesPositions.push(p1.x);
  79748. this._linesPositions.push(p1.y);
  79749. this._linesPositions.push(p1.z);
  79750. // Normals
  79751. this._linesNormals.push(p1.x);
  79752. this._linesNormals.push(p1.y);
  79753. this._linesNormals.push(p1.z);
  79754. this._linesNormals.push(-1);
  79755. this._linesNormals.push(p1.x);
  79756. this._linesNormals.push(p1.y);
  79757. this._linesNormals.push(p1.z);
  79758. this._linesNormals.push(1);
  79759. this._linesNormals.push(p0.x);
  79760. this._linesNormals.push(p0.y);
  79761. this._linesNormals.push(p0.z);
  79762. this._linesNormals.push(-1);
  79763. this._linesNormals.push(p0.x);
  79764. this._linesNormals.push(p0.y);
  79765. this._linesNormals.push(p0.z);
  79766. this._linesNormals.push(1);
  79767. // Indices
  79768. this._linesIndices.push(offset);
  79769. this._linesIndices.push(offset + 1);
  79770. this._linesIndices.push(offset + 2);
  79771. this._linesIndices.push(offset);
  79772. this._linesIndices.push(offset + 2);
  79773. this._linesIndices.push(offset + 3);
  79774. }
  79775. };
  79776. EdgesRenderer.prototype._generateEdgesLines = function () {
  79777. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  79778. var indices = this._source.getIndices();
  79779. if (!indices || !positions) {
  79780. return;
  79781. }
  79782. // First let's find adjacencies
  79783. var adjacencies = new Array();
  79784. var faceNormals = new Array();
  79785. var index;
  79786. var faceAdjacencies;
  79787. // Prepare faces
  79788. for (index = 0; index < indices.length; index += 3) {
  79789. faceAdjacencies = new FaceAdjacencies();
  79790. var p0Index = indices[index];
  79791. var p1Index = indices[index + 1];
  79792. var p2Index = indices[index + 2];
  79793. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  79794. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  79795. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  79796. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  79797. faceNormal.normalize();
  79798. faceNormals.push(faceNormal);
  79799. adjacencies.push(faceAdjacencies);
  79800. }
  79801. // Scan
  79802. for (index = 0; index < adjacencies.length; index++) {
  79803. faceAdjacencies = adjacencies[index];
  79804. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  79805. var otherFaceAdjacencies = adjacencies[otherIndex];
  79806. if (faceAdjacencies.edgesConnectedCount === 3) {
  79807. break;
  79808. }
  79809. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  79810. continue;
  79811. }
  79812. var otherP0 = indices[otherIndex * 3];
  79813. var otherP1 = indices[otherIndex * 3 + 1];
  79814. var otherP2 = indices[otherIndex * 3 + 2];
  79815. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  79816. var otherEdgeIndex = 0;
  79817. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  79818. continue;
  79819. }
  79820. switch (edgeIndex) {
  79821. case 0:
  79822. if (this._checkVerticesInsteadOfIndices) {
  79823. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79824. }
  79825. else {
  79826. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  79827. }
  79828. break;
  79829. case 1:
  79830. if (this._checkVerticesInsteadOfIndices) {
  79831. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79832. }
  79833. else {
  79834. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  79835. }
  79836. break;
  79837. case 2:
  79838. if (this._checkVerticesInsteadOfIndices) {
  79839. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79840. }
  79841. else {
  79842. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  79843. }
  79844. break;
  79845. }
  79846. if (otherEdgeIndex === -1) {
  79847. continue;
  79848. }
  79849. faceAdjacencies.edges[edgeIndex] = otherIndex;
  79850. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  79851. faceAdjacencies.edgesConnectedCount++;
  79852. otherFaceAdjacencies.edgesConnectedCount++;
  79853. if (faceAdjacencies.edgesConnectedCount === 3) {
  79854. break;
  79855. }
  79856. }
  79857. }
  79858. }
  79859. // Create lines
  79860. for (index = 0; index < adjacencies.length; index++) {
  79861. // 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
  79862. var current = adjacencies[index];
  79863. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  79864. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  79865. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  79866. }
  79867. // Merge into a single mesh
  79868. var engine = this._source.getScene().getEngine();
  79869. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  79870. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  79871. this._ib = engine.createIndexBuffer(this._linesIndices);
  79872. this._indicesCount = this._linesIndices.length;
  79873. };
  79874. EdgesRenderer.prototype.render = function () {
  79875. var scene = this._source.getScene();
  79876. if (!this._lineShader.isReady() || !scene.activeCamera) {
  79877. return;
  79878. }
  79879. var engine = scene.getEngine();
  79880. this._lineShader._preBind();
  79881. // VBOs
  79882. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  79883. scene.resetCachedMaterial();
  79884. this._lineShader.setColor4("color", this._source.edgesColor);
  79885. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  79886. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  79887. }
  79888. else {
  79889. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  79890. }
  79891. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  79892. this._lineShader.bind(this._source.getWorldMatrix());
  79893. // Draw order
  79894. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  79895. this._lineShader.unbind();
  79896. engine.setDepthWrite(true);
  79897. };
  79898. return EdgesRenderer;
  79899. }());
  79900. BABYLON.EdgesRenderer = EdgesRenderer;
  79901. })(BABYLON || (BABYLON = {}));
  79902. //# sourceMappingURL=babylon.edgesRenderer.js.map
  79903. var BABYLON;
  79904. (function (BABYLON) {
  79905. /**
  79906. * Special Glow Blur post process only blurring the alpha channel
  79907. * It enforces keeping the most luminous color in the color channel.
  79908. */
  79909. var GlowBlurPostProcess = /** @class */ (function (_super) {
  79910. __extends(GlowBlurPostProcess, _super);
  79911. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  79912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79913. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  79914. _this.direction = direction;
  79915. _this.kernel = kernel;
  79916. _this.onApplyObservable.add(function (effect) {
  79917. effect.setFloat2("screenSize", _this.width, _this.height);
  79918. effect.setVector2("direction", _this.direction);
  79919. effect.setFloat("blurWidth", _this.kernel);
  79920. });
  79921. return _this;
  79922. }
  79923. return GlowBlurPostProcess;
  79924. }(BABYLON.PostProcess));
  79925. /**
  79926. * The highlight layer Helps adding a glow effect around a mesh.
  79927. *
  79928. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  79929. * glowy meshes to your scene.
  79930. *
  79931. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  79932. */
  79933. var HighlightLayer = /** @class */ (function () {
  79934. /**
  79935. * Instantiates a new highlight Layer and references it to the scene..
  79936. * @param name The name of the layer
  79937. * @param scene The scene to use the layer in
  79938. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  79939. */
  79940. function HighlightLayer(name, scene, options) {
  79941. this.name = name;
  79942. this._vertexBuffers = {};
  79943. this._mainTextureDesiredSize = { width: 0, height: 0 };
  79944. this._meshes = {};
  79945. this._maxSize = 0;
  79946. this._shouldRender = false;
  79947. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  79948. this._excludedMeshes = {};
  79949. /**
  79950. * Specifies whether or not the inner glow is ACTIVE in the layer.
  79951. */
  79952. this.innerGlow = true;
  79953. /**
  79954. * Specifies whether or not the outer glow is ACTIVE in the layer.
  79955. */
  79956. this.outerGlow = true;
  79957. /**
  79958. * Specifies wether the highlight layer is enabled or not.
  79959. */
  79960. this.isEnabled = true;
  79961. /**
  79962. * An event triggered when the highlight layer has been disposed.
  79963. * @type {BABYLON.Observable}
  79964. */
  79965. this.onDisposeObservable = new BABYLON.Observable();
  79966. /**
  79967. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  79968. * @type {BABYLON.Observable}
  79969. */
  79970. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  79971. /**
  79972. * An event triggered when the highlight layer is being blurred.
  79973. * @type {BABYLON.Observable}
  79974. */
  79975. this.onBeforeBlurObservable = new BABYLON.Observable();
  79976. /**
  79977. * An event triggered when the highlight layer has been blurred.
  79978. * @type {BABYLON.Observable}
  79979. */
  79980. this.onAfterBlurObservable = new BABYLON.Observable();
  79981. /**
  79982. * An event triggered when the glowing blurred texture is being merged in the scene.
  79983. * @type {BABYLON.Observable}
  79984. */
  79985. this.onBeforeComposeObservable = new BABYLON.Observable();
  79986. /**
  79987. * An event triggered when the glowing blurred texture has been merged in the scene.
  79988. * @type {BABYLON.Observable}
  79989. */
  79990. this.onAfterComposeObservable = new BABYLON.Observable();
  79991. /**
  79992. * An event triggered when the highlight layer changes its size.
  79993. * @type {BABYLON.Observable}
  79994. */
  79995. this.onSizeChangedObservable = new BABYLON.Observable();
  79996. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79997. var engine = scene.getEngine();
  79998. this._engine = engine;
  79999. this._maxSize = this._engine.getCaps().maxTextureSize;
  80000. this._scene.highlightLayers.push(this);
  80001. // Warn on stencil.
  80002. if (!this._engine.isStencilEnable) {
  80003. 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 }");
  80004. }
  80005. // Adapt options
  80006. this._options = options || {
  80007. mainTextureRatio: 0.5,
  80008. blurTextureSizeRatio: 0.5,
  80009. blurHorizontalSize: 1.0,
  80010. blurVerticalSize: 1.0,
  80011. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  80012. camera: null
  80013. };
  80014. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  80015. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  80016. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  80017. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  80018. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  80019. // VBO
  80020. var vertices = [];
  80021. vertices.push(1, 1);
  80022. vertices.push(-1, 1);
  80023. vertices.push(-1, -1);
  80024. vertices.push(1, -1);
  80025. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80026. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80027. this._createIndexBuffer();
  80028. // Effect
  80029. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  80030. // Render target
  80031. this.setMainTextureSize();
  80032. // Create Textures and post processes
  80033. this.createTextureAndPostProcesses();
  80034. }
  80035. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  80036. /**
  80037. * Gets the horizontal size of the blur.
  80038. */
  80039. get: function () {
  80040. return this._horizontalBlurPostprocess.kernel;
  80041. },
  80042. /**
  80043. * Specifies the horizontal size of the blur.
  80044. */
  80045. set: function (value) {
  80046. this._horizontalBlurPostprocess.kernel = value;
  80047. },
  80048. enumerable: true,
  80049. configurable: true
  80050. });
  80051. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  80052. /**
  80053. * Gets the vertical size of the blur.
  80054. */
  80055. get: function () {
  80056. return this._verticalBlurPostprocess.kernel;
  80057. },
  80058. /**
  80059. * Specifies the vertical size of the blur.
  80060. */
  80061. set: function (value) {
  80062. this._verticalBlurPostprocess.kernel = value;
  80063. },
  80064. enumerable: true,
  80065. configurable: true
  80066. });
  80067. Object.defineProperty(HighlightLayer.prototype, "camera", {
  80068. /**
  80069. * Gets the camera attached to the layer.
  80070. */
  80071. get: function () {
  80072. return this._options.camera;
  80073. },
  80074. enumerable: true,
  80075. configurable: true
  80076. });
  80077. HighlightLayer.prototype._createIndexBuffer = function () {
  80078. var engine = this._scene.getEngine();
  80079. // Indices
  80080. var indices = [];
  80081. indices.push(0);
  80082. indices.push(1);
  80083. indices.push(2);
  80084. indices.push(0);
  80085. indices.push(2);
  80086. indices.push(3);
  80087. this._indexBuffer = engine.createIndexBuffer(indices);
  80088. };
  80089. HighlightLayer.prototype._rebuild = function () {
  80090. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80091. if (vb) {
  80092. vb._rebuild();
  80093. }
  80094. this._createIndexBuffer();
  80095. };
  80096. /**
  80097. * Creates the render target textures and post processes used in the highlight layer.
  80098. */
  80099. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  80100. var _this = this;
  80101. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  80102. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  80103. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  80104. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  80105. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  80106. width: this._mainTextureDesiredSize.width,
  80107. height: this._mainTextureDesiredSize.height
  80108. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80109. this._mainTexture.activeCamera = this._options.camera;
  80110. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80111. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80112. this._mainTexture.anisotropicFilteringLevel = 1;
  80113. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80114. this._mainTexture.renderParticles = false;
  80115. this._mainTexture.renderList = null;
  80116. this._mainTexture.ignoreCameraViewport = true;
  80117. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  80118. width: blurTextureWidth,
  80119. height: blurTextureHeight
  80120. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80121. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80122. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80123. this._blurTexture.anisotropicFilteringLevel = 16;
  80124. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80125. this._blurTexture.renderParticles = false;
  80126. this._blurTexture.ignoreCameraViewport = true;
  80127. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80128. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  80129. effect.setTexture("textureSampler", _this._mainTexture);
  80130. });
  80131. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  80132. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80133. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80134. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80135. });
  80136. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80137. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80138. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80139. });
  80140. }
  80141. else {
  80142. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80143. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  80144. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80145. });
  80146. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  80147. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  80148. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  80149. });
  80150. }
  80151. this._mainTexture.onAfterUnbindObservable.add(function () {
  80152. _this.onBeforeBlurObservable.notifyObservers(_this);
  80153. var internalTexture = _this._blurTexture.getInternalTexture();
  80154. if (internalTexture) {
  80155. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  80156. }
  80157. _this.onAfterBlurObservable.notifyObservers(_this);
  80158. });
  80159. // Custom render function
  80160. var renderSubMesh = function (subMesh) {
  80161. if (!_this._meshes) {
  80162. return;
  80163. }
  80164. var material = subMesh.getMaterial();
  80165. var mesh = subMesh.getRenderingMesh();
  80166. var scene = _this._scene;
  80167. var engine = scene.getEngine();
  80168. if (!material) {
  80169. return;
  80170. }
  80171. // Do not block in blend mode.
  80172. if (material.needAlphaBlendingForMesh(mesh)) {
  80173. return;
  80174. }
  80175. // Culling
  80176. engine.setState(material.backFaceCulling);
  80177. // Managing instances
  80178. var batch = mesh._getInstancesRenderList(subMesh._id);
  80179. if (batch.mustReturn) {
  80180. return;
  80181. }
  80182. // Excluded Mesh
  80183. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80184. return;
  80185. }
  80186. ;
  80187. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  80188. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  80189. var emissiveTexture = null;
  80190. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80191. emissiveTexture = material.emissiveTexture;
  80192. }
  80193. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  80194. engine.enableEffect(_this._glowMapGenerationEffect);
  80195. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  80196. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  80197. if (highlightLayerMesh) {
  80198. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  80199. }
  80200. else {
  80201. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  80202. }
  80203. // Alpha test
  80204. if (material && material.needAlphaTesting()) {
  80205. var alphaTexture = material.getAlphaTestTexture();
  80206. if (alphaTexture) {
  80207. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  80208. var textureMatrix = alphaTexture.getTextureMatrix();
  80209. if (textureMatrix) {
  80210. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  80211. }
  80212. }
  80213. }
  80214. // Glow emissive only
  80215. if (emissiveTexture) {
  80216. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  80217. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  80218. }
  80219. // Bones
  80220. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80221. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80222. }
  80223. // Draw
  80224. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  80225. }
  80226. else {
  80227. // Need to reset refresh rate of the shadowMap
  80228. _this._mainTexture.resetRefreshCounter();
  80229. }
  80230. };
  80231. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80232. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  80233. var index;
  80234. var engine = _this._scene.getEngine();
  80235. if (depthOnlySubMeshes.length) {
  80236. engine.setColorWrite(false);
  80237. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80238. renderSubMesh(depthOnlySubMeshes.data[index]);
  80239. }
  80240. engine.setColorWrite(true);
  80241. }
  80242. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80243. renderSubMesh(opaqueSubMeshes.data[index]);
  80244. }
  80245. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80246. renderSubMesh(alphaTestSubMeshes.data[index]);
  80247. }
  80248. for (index = 0; index < transparentSubMeshes.length; index++) {
  80249. renderSubMesh(transparentSubMeshes.data[index]);
  80250. }
  80251. };
  80252. this._mainTexture.onClearObservable.add(function (engine) {
  80253. engine.clear(HighlightLayer.neutralColor, true, true, true);
  80254. });
  80255. };
  80256. /**
  80257. * Checks for the readiness of the element composing the layer.
  80258. * @param subMesh the mesh to check for
  80259. * @param useInstances specify wether or not to use instances to render the mesh
  80260. * @param emissiveTexture the associated emissive texture used to generate the glow
  80261. * @return true if ready otherwise, false
  80262. */
  80263. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  80264. var material = subMesh.getMaterial();
  80265. var mesh = subMesh.getRenderingMesh();
  80266. if (!material || !mesh || !this._meshes) {
  80267. return false;
  80268. }
  80269. var emissiveTexture = null;
  80270. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  80271. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  80272. emissiveTexture = material.emissiveTexture;
  80273. }
  80274. return this._isReady(subMesh, useInstances, emissiveTexture);
  80275. };
  80276. /**
  80277. * Checks for the readiness of the element composing the layer.
  80278. * @param subMesh the mesh to check for
  80279. * @param useInstances specify wether or not to use instances to render the mesh
  80280. * @param emissiveTexture the associated emissive texture used to generate the glow
  80281. * @return true if ready otherwise, false
  80282. */
  80283. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  80284. var material = subMesh.getMaterial();
  80285. if (!material) {
  80286. return false;
  80287. }
  80288. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  80289. return false;
  80290. }
  80291. var defines = [];
  80292. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80293. var mesh = subMesh.getMesh();
  80294. var uv1 = false;
  80295. var uv2 = false;
  80296. // Alpha test
  80297. if (material && material.needAlphaTesting()) {
  80298. var alphaTexture = material.getAlphaTestTexture();
  80299. if (alphaTexture) {
  80300. defines.push("#define ALPHATEST");
  80301. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80302. alphaTexture.coordinatesIndex === 1) {
  80303. defines.push("#define DIFFUSEUV2");
  80304. uv2 = true;
  80305. }
  80306. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80307. defines.push("#define DIFFUSEUV1");
  80308. uv1 = true;
  80309. }
  80310. }
  80311. }
  80312. // Emissive
  80313. if (emissiveTexture) {
  80314. defines.push("#define EMISSIVE");
  80315. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  80316. emissiveTexture.coordinatesIndex === 1) {
  80317. defines.push("#define EMISSIVEUV2");
  80318. uv2 = true;
  80319. }
  80320. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80321. defines.push("#define EMISSIVEUV1");
  80322. uv1 = true;
  80323. }
  80324. }
  80325. if (uv1) {
  80326. attribs.push(BABYLON.VertexBuffer.UVKind);
  80327. defines.push("#define UV1");
  80328. }
  80329. if (uv2) {
  80330. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80331. defines.push("#define UV2");
  80332. }
  80333. // Bones
  80334. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80335. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80336. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80337. if (mesh.numBoneInfluencers > 4) {
  80338. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80339. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80340. }
  80341. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80342. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80343. }
  80344. else {
  80345. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80346. }
  80347. // Instances
  80348. if (useInstances) {
  80349. defines.push("#define INSTANCES");
  80350. attribs.push("world0");
  80351. attribs.push("world1");
  80352. attribs.push("world2");
  80353. attribs.push("world3");
  80354. }
  80355. // Get correct effect
  80356. var join = defines.join("\n");
  80357. if (this._cachedDefines !== join) {
  80358. this._cachedDefines = join;
  80359. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  80360. }
  80361. return this._glowMapGenerationEffect.isReady();
  80362. };
  80363. /**
  80364. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  80365. */
  80366. HighlightLayer.prototype.render = function () {
  80367. var currentEffect = this._glowMapMergeEffect;
  80368. // Check
  80369. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  80370. return;
  80371. var engine = this._scene.getEngine();
  80372. this.onBeforeComposeObservable.notifyObservers(this);
  80373. // Render
  80374. engine.enableEffect(currentEffect);
  80375. engine.setState(false);
  80376. // Cache
  80377. var previousStencilBuffer = engine.getStencilBuffer();
  80378. var previousStencilFunction = engine.getStencilFunction();
  80379. var previousStencilMask = engine.getStencilMask();
  80380. var previousStencilOperationPass = engine.getStencilOperationPass();
  80381. var previousStencilOperationFail = engine.getStencilOperationFail();
  80382. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  80383. var previousAlphaMode = engine.getAlphaMode();
  80384. // Texture
  80385. currentEffect.setTexture("textureSampler", this._blurTexture);
  80386. // VBOs
  80387. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80388. // Stencil operations
  80389. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  80390. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  80391. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  80392. // Draw order
  80393. engine.setAlphaMode(this._options.alphaBlendingMode);
  80394. engine.setStencilMask(0x00);
  80395. engine.setStencilBuffer(true);
  80396. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  80397. if (this.outerGlow) {
  80398. currentEffect.setFloat("offset", 0);
  80399. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  80400. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80401. }
  80402. if (this.innerGlow) {
  80403. currentEffect.setFloat("offset", 1);
  80404. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  80405. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80406. }
  80407. // Restore Cache
  80408. engine.setStencilFunction(previousStencilFunction);
  80409. engine.setStencilMask(previousStencilMask);
  80410. engine.setAlphaMode(previousAlphaMode);
  80411. engine.setStencilBuffer(previousStencilBuffer);
  80412. engine.setStencilOperationPass(previousStencilOperationPass);
  80413. engine.setStencilOperationFail(previousStencilOperationFail);
  80414. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  80415. engine._stencilState.reset();
  80416. this.onAfterComposeObservable.notifyObservers(this);
  80417. // Handle size changes.
  80418. var size = this._mainTexture.getSize();
  80419. this.setMainTextureSize();
  80420. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  80421. // Recreate RTT and post processes on size change.
  80422. this.onSizeChangedObservable.notifyObservers(this);
  80423. this.disposeTextureAndPostProcesses();
  80424. this.createTextureAndPostProcesses();
  80425. }
  80426. };
  80427. /**
  80428. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  80429. * @param mesh The mesh to exclude from the highlight layer
  80430. */
  80431. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  80432. if (!this._excludedMeshes) {
  80433. return;
  80434. }
  80435. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80436. if (!meshExcluded) {
  80437. this._excludedMeshes[mesh.uniqueId] = {
  80438. mesh: mesh,
  80439. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  80440. mesh.getEngine().setStencilBuffer(false);
  80441. }),
  80442. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  80443. mesh.getEngine().setStencilBuffer(true);
  80444. }),
  80445. };
  80446. }
  80447. };
  80448. /**
  80449. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  80450. * @param mesh The mesh to highlight
  80451. */
  80452. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  80453. if (!this._excludedMeshes) {
  80454. return;
  80455. }
  80456. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  80457. if (meshExcluded) {
  80458. if (meshExcluded.beforeRender) {
  80459. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  80460. }
  80461. if (meshExcluded.afterRender) {
  80462. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  80463. }
  80464. }
  80465. this._excludedMeshes[mesh.uniqueId] = null;
  80466. };
  80467. /**
  80468. * Determine if a given mesh will be highlighted by the current HighlightLayer
  80469. * @param mesh mesh to test
  80470. * @returns true if the mesh will be highlighted by the current HighlightLayer
  80471. */
  80472. HighlightLayer.prototype.hasMesh = function (mesh) {
  80473. if (!this._meshes) {
  80474. return false;
  80475. }
  80476. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  80477. };
  80478. /**
  80479. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  80480. * @param mesh The mesh to highlight
  80481. * @param color The color of the highlight
  80482. * @param glowEmissiveOnly Extract the glow from the emissive texture
  80483. */
  80484. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  80485. var _this = this;
  80486. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  80487. if (!this._meshes) {
  80488. return;
  80489. }
  80490. var meshHighlight = this._meshes[mesh.uniqueId];
  80491. if (meshHighlight) {
  80492. meshHighlight.color = color;
  80493. }
  80494. else {
  80495. this._meshes[mesh.uniqueId] = {
  80496. mesh: mesh,
  80497. color: color,
  80498. // Lambda required for capture due to Observable this context
  80499. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  80500. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  80501. _this.defaultStencilReference(mesh);
  80502. }
  80503. else {
  80504. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  80505. }
  80506. }),
  80507. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  80508. glowEmissiveOnly: glowEmissiveOnly
  80509. };
  80510. }
  80511. this._shouldRender = true;
  80512. };
  80513. /**
  80514. * Remove a mesh from the highlight layer in order to make it stop glowing.
  80515. * @param mesh The mesh to highlight
  80516. */
  80517. HighlightLayer.prototype.removeMesh = function (mesh) {
  80518. if (!this._meshes) {
  80519. return;
  80520. }
  80521. var meshHighlight = this._meshes[mesh.uniqueId];
  80522. if (meshHighlight) {
  80523. if (meshHighlight.observerHighlight) {
  80524. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80525. }
  80526. if (meshHighlight.observerDefault) {
  80527. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80528. }
  80529. delete this._meshes[mesh.uniqueId];
  80530. }
  80531. this._shouldRender = false;
  80532. for (var meshHighlightToCheck in this._meshes) {
  80533. if (this._meshes[meshHighlightToCheck]) {
  80534. this._shouldRender = true;
  80535. break;
  80536. }
  80537. }
  80538. };
  80539. /**
  80540. * Returns true if the layer contains information to display, otherwise false.
  80541. */
  80542. HighlightLayer.prototype.shouldRender = function () {
  80543. return this.isEnabled && this._shouldRender;
  80544. };
  80545. /**
  80546. * Sets the main texture desired size which is the closest power of two
  80547. * of the engine canvas size.
  80548. */
  80549. HighlightLayer.prototype.setMainTextureSize = function () {
  80550. if (this._options.mainTextureFixedSize) {
  80551. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  80552. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  80553. }
  80554. else {
  80555. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  80556. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  80557. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  80558. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  80559. }
  80560. };
  80561. /**
  80562. * Force the stencil to the normal expected value for none glowing parts
  80563. */
  80564. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  80565. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  80566. };
  80567. /**
  80568. * Dispose only the render target textures and post process.
  80569. */
  80570. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  80571. this._blurTexture.dispose();
  80572. this._mainTexture.dispose();
  80573. this._downSamplePostprocess.dispose();
  80574. this._horizontalBlurPostprocess.dispose();
  80575. this._verticalBlurPostprocess.dispose();
  80576. };
  80577. /**
  80578. * Dispose the highlight layer and free resources.
  80579. */
  80580. HighlightLayer.prototype.dispose = function () {
  80581. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80582. if (vertexBuffer) {
  80583. vertexBuffer.dispose();
  80584. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80585. }
  80586. if (this._indexBuffer) {
  80587. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80588. this._indexBuffer = null;
  80589. }
  80590. // Clean textures and post processes
  80591. this.disposeTextureAndPostProcesses();
  80592. if (this._meshes) {
  80593. // Clean mesh references
  80594. for (var id in this._meshes) {
  80595. var meshHighlight = this._meshes[id];
  80596. if (meshHighlight && meshHighlight.mesh) {
  80597. if (meshHighlight.observerHighlight) {
  80598. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  80599. }
  80600. if (meshHighlight.observerDefault) {
  80601. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  80602. }
  80603. }
  80604. }
  80605. this._meshes = null;
  80606. }
  80607. if (this._excludedMeshes) {
  80608. for (var id in this._excludedMeshes) {
  80609. var meshHighlight = this._excludedMeshes[id];
  80610. if (meshHighlight) {
  80611. if (meshHighlight.beforeRender) {
  80612. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  80613. }
  80614. if (meshHighlight.afterRender) {
  80615. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  80616. }
  80617. }
  80618. }
  80619. this._excludedMeshes = null;
  80620. }
  80621. // Remove from scene
  80622. var index = this._scene.highlightLayers.indexOf(this, 0);
  80623. if (index > -1) {
  80624. this._scene.highlightLayers.splice(index, 1);
  80625. }
  80626. // Callback
  80627. this.onDisposeObservable.notifyObservers(this);
  80628. this.onDisposeObservable.clear();
  80629. this.onBeforeRenderMainTextureObservable.clear();
  80630. this.onBeforeBlurObservable.clear();
  80631. this.onBeforeComposeObservable.clear();
  80632. this.onAfterComposeObservable.clear();
  80633. this.onSizeChangedObservable.clear();
  80634. };
  80635. /**
  80636. * The neutral color used during the preparation of the glow effect.
  80637. * This is black by default as the blend operation is a blend operation.
  80638. */
  80639. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  80640. /**
  80641. * Stencil value used for glowing meshes.
  80642. */
  80643. HighlightLayer.glowingMeshStencilReference = 0x02;
  80644. /**
  80645. * Stencil value used for the other meshes in the scene.
  80646. */
  80647. HighlightLayer.normalMeshStencilReference = 0x01;
  80648. return HighlightLayer;
  80649. }());
  80650. BABYLON.HighlightLayer = HighlightLayer;
  80651. })(BABYLON || (BABYLON = {}));
  80652. //# sourceMappingURL=babylon.highlightlayer.js.map
  80653. var BABYLON;
  80654. (function (BABYLON) {
  80655. /**
  80656. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  80657. */
  80658. var AssetTaskState;
  80659. (function (AssetTaskState) {
  80660. /**
  80661. * Initialization
  80662. */
  80663. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  80664. /**
  80665. * Running
  80666. */
  80667. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  80668. /**
  80669. * Done
  80670. */
  80671. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  80672. /**
  80673. * Error
  80674. */
  80675. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  80676. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  80677. /**
  80678. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  80679. */
  80680. var AbstractAssetTask = /** @class */ (function () {
  80681. /**
  80682. * Creates a new {BABYLON.AssetsManager}
  80683. * @param name defines the name of the task
  80684. */
  80685. function AbstractAssetTask(
  80686. /**
  80687. * Task name
  80688. */ name) {
  80689. this.name = name;
  80690. this._isCompleted = false;
  80691. this._taskState = AssetTaskState.INIT;
  80692. }
  80693. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  80694. /**
  80695. * Get if the task is completed
  80696. */
  80697. get: function () {
  80698. return this._isCompleted;
  80699. },
  80700. enumerable: true,
  80701. configurable: true
  80702. });
  80703. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  80704. /**
  80705. * Gets the current state of the task
  80706. */
  80707. get: function () {
  80708. return this._taskState;
  80709. },
  80710. enumerable: true,
  80711. configurable: true
  80712. });
  80713. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  80714. /**
  80715. * Gets the current error object (if task is in error)
  80716. */
  80717. get: function () {
  80718. return this._errorObject;
  80719. },
  80720. enumerable: true,
  80721. configurable: true
  80722. });
  80723. /**
  80724. * Internal only
  80725. * @ignore
  80726. */
  80727. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  80728. if (this._errorObject) {
  80729. return;
  80730. }
  80731. this._errorObject = {
  80732. message: message,
  80733. exception: exception
  80734. };
  80735. };
  80736. /**
  80737. * Execute the current task
  80738. * @param scene defines the scene where you want your assets to be loaded
  80739. * @param onSuccess is a callback called when the task is successfully executed
  80740. * @param onError is a callback called if an error occurs
  80741. */
  80742. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  80743. var _this = this;
  80744. this._taskState = AssetTaskState.RUNNING;
  80745. this.runTask(scene, function () {
  80746. _this.onDoneCallback(onSuccess, onError);
  80747. }, function (msg, exception) {
  80748. _this.onErrorCallback(onError, msg, exception);
  80749. });
  80750. };
  80751. /**
  80752. * Execute the current task
  80753. * @param scene defines the scene where you want your assets to be loaded
  80754. * @param onSuccess is a callback called when the task is successfully executed
  80755. * @param onError is a callback called if an error occurs
  80756. */
  80757. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80758. throw new Error("runTask is not implemented");
  80759. };
  80760. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  80761. this._taskState = AssetTaskState.ERROR;
  80762. this._errorObject = {
  80763. message: message,
  80764. exception: exception
  80765. };
  80766. if (this.onError) {
  80767. this.onError(this, message, exception);
  80768. }
  80769. onError();
  80770. };
  80771. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  80772. try {
  80773. this._taskState = AssetTaskState.DONE;
  80774. this._isCompleted = true;
  80775. if (this.onSuccess) {
  80776. this.onSuccess(this);
  80777. }
  80778. onSuccess();
  80779. }
  80780. catch (e) {
  80781. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  80782. }
  80783. };
  80784. return AbstractAssetTask;
  80785. }());
  80786. BABYLON.AbstractAssetTask = AbstractAssetTask;
  80787. /**
  80788. * Class used to share progress information about assets loading
  80789. */
  80790. var AssetsProgressEvent = /** @class */ (function () {
  80791. /**
  80792. * Creates a {BABYLON.AssetsProgressEvent}
  80793. * @param remainingCount defines the number of remaining tasks to process
  80794. * @param totalCount defines the total number of tasks
  80795. * @param task defines the task that was just processed
  80796. */
  80797. function AssetsProgressEvent(remainingCount, totalCount, task) {
  80798. this.remainingCount = remainingCount;
  80799. this.totalCount = totalCount;
  80800. this.task = task;
  80801. }
  80802. return AssetsProgressEvent;
  80803. }());
  80804. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  80805. /**
  80806. * Define a task used by {BABYLON.AssetsManager} to load meshes
  80807. */
  80808. var MeshAssetTask = /** @class */ (function (_super) {
  80809. __extends(MeshAssetTask, _super);
  80810. /**
  80811. * Creates a new {BABYLON.MeshAssetTask}
  80812. * @param name defines the name of the task
  80813. * @param meshesNames defines the list of mesh's names you want to load
  80814. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  80815. * @param sceneFilename defines the filename of the scene to load from
  80816. */
  80817. function MeshAssetTask(
  80818. /**
  80819. * Defines the name of the task
  80820. */
  80821. name,
  80822. /**
  80823. * Defines the list of mesh's names you want to load
  80824. */
  80825. meshesNames,
  80826. /**
  80827. * Defines the root url to use as a base to load your meshes and associated resources
  80828. */
  80829. rootUrl,
  80830. /**
  80831. * Defines the filename of the scene to load from
  80832. */
  80833. sceneFilename) {
  80834. var _this = _super.call(this, name) || this;
  80835. _this.name = name;
  80836. _this.meshesNames = meshesNames;
  80837. _this.rootUrl = rootUrl;
  80838. _this.sceneFilename = sceneFilename;
  80839. return _this;
  80840. }
  80841. /**
  80842. * Execute the current task
  80843. * @param scene defines the scene where you want your assets to be loaded
  80844. * @param onSuccess is a callback called when the task is successfully executed
  80845. * @param onError is a callback called if an error occurs
  80846. */
  80847. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80848. var _this = this;
  80849. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  80850. _this.loadedMeshes = meshes;
  80851. _this.loadedParticleSystems = particleSystems;
  80852. _this.loadedSkeletons = skeletons;
  80853. onSuccess();
  80854. }, null, function (scene, message, exception) {
  80855. onError(message, exception);
  80856. });
  80857. };
  80858. return MeshAssetTask;
  80859. }(AbstractAssetTask));
  80860. BABYLON.MeshAssetTask = MeshAssetTask;
  80861. /**
  80862. * Define a task used by {BABYLON.AssetsManager} to load text content
  80863. */
  80864. var TextFileAssetTask = /** @class */ (function (_super) {
  80865. __extends(TextFileAssetTask, _super);
  80866. /**
  80867. * Creates a new TextFileAssetTask object
  80868. * @param name defines the name of the task
  80869. * @param url defines the location of the file to load
  80870. */
  80871. function TextFileAssetTask(
  80872. /**
  80873. * Defines the name of the task
  80874. */
  80875. name,
  80876. /**
  80877. * Defines the location of the file to load
  80878. */
  80879. url) {
  80880. var _this = _super.call(this, name) || this;
  80881. _this.name = name;
  80882. _this.url = url;
  80883. return _this;
  80884. }
  80885. /**
  80886. * Execute the current task
  80887. * @param scene defines the scene where you want your assets to be loaded
  80888. * @param onSuccess is a callback called when the task is successfully executed
  80889. * @param onError is a callback called if an error occurs
  80890. */
  80891. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80892. var _this = this;
  80893. scene._loadFile(this.url, function (data) {
  80894. _this.text = data;
  80895. onSuccess();
  80896. }, undefined, false, true, function (request, exception) {
  80897. if (request) {
  80898. onError(request.status + " " + request.statusText, exception);
  80899. }
  80900. });
  80901. };
  80902. return TextFileAssetTask;
  80903. }(AbstractAssetTask));
  80904. BABYLON.TextFileAssetTask = TextFileAssetTask;
  80905. /**
  80906. * Define a task used by {BABYLON.AssetsManager} to load binary data
  80907. */
  80908. var BinaryFileAssetTask = /** @class */ (function (_super) {
  80909. __extends(BinaryFileAssetTask, _super);
  80910. /**
  80911. * Creates a new BinaryFileAssetTask object
  80912. * @param name defines the name of the new task
  80913. * @param url defines the location of the file to load
  80914. */
  80915. function BinaryFileAssetTask(
  80916. /**
  80917. * Defines the name of the task
  80918. */
  80919. name,
  80920. /**
  80921. * Defines the location of the file to load
  80922. */
  80923. url) {
  80924. var _this = _super.call(this, name) || this;
  80925. _this.name = name;
  80926. _this.url = url;
  80927. return _this;
  80928. }
  80929. /**
  80930. * Execute the current task
  80931. * @param scene defines the scene where you want your assets to be loaded
  80932. * @param onSuccess is a callback called when the task is successfully executed
  80933. * @param onError is a callback called if an error occurs
  80934. */
  80935. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80936. var _this = this;
  80937. scene._loadFile(this.url, function (data) {
  80938. _this.data = data;
  80939. onSuccess();
  80940. }, undefined, true, true, function (request, exception) {
  80941. if (request) {
  80942. onError(request.status + " " + request.statusText, exception);
  80943. }
  80944. });
  80945. };
  80946. return BinaryFileAssetTask;
  80947. }(AbstractAssetTask));
  80948. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  80949. /**
  80950. * Define a task used by {BABYLON.AssetsManager} to load images
  80951. */
  80952. var ImageAssetTask = /** @class */ (function (_super) {
  80953. __extends(ImageAssetTask, _super);
  80954. /**
  80955. * Creates a new ImageAssetTask
  80956. * @param name defines the name of the task
  80957. * @param url defines the location of the image to load
  80958. */
  80959. function ImageAssetTask(
  80960. /**
  80961. * Defines the name of the task
  80962. */
  80963. name,
  80964. /**
  80965. * Defines the location of the image to load
  80966. */
  80967. url) {
  80968. var _this = _super.call(this, name) || this;
  80969. _this.name = name;
  80970. _this.url = url;
  80971. return _this;
  80972. }
  80973. /**
  80974. * Execute the current task
  80975. * @param scene defines the scene where you want your assets to be loaded
  80976. * @param onSuccess is a callback called when the task is successfully executed
  80977. * @param onError is a callback called if an error occurs
  80978. */
  80979. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80980. var _this = this;
  80981. var img = new Image();
  80982. BABYLON.Tools.SetCorsBehavior(this.url, img);
  80983. img.onload = function () {
  80984. _this.image = img;
  80985. onSuccess();
  80986. };
  80987. img.onerror = function (err) {
  80988. onError("Error loading image", err);
  80989. };
  80990. img.src = this.url;
  80991. };
  80992. return ImageAssetTask;
  80993. }(AbstractAssetTask));
  80994. BABYLON.ImageAssetTask = ImageAssetTask;
  80995. /**
  80996. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  80997. */
  80998. var TextureAssetTask = /** @class */ (function (_super) {
  80999. __extends(TextureAssetTask, _super);
  81000. /**
  81001. * Creates a new TextureAssetTask object
  81002. * @param name defines the name of the task
  81003. * @param url defines the location of the file to load
  81004. * @param noMipmap defines if mipmap should not be generated (default is false)
  81005. * @param invertY defines if texture must be inverted on Y axis (default is false)
  81006. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81007. */
  81008. function TextureAssetTask(
  81009. /**
  81010. * Defines the name of the task
  81011. */
  81012. name,
  81013. /**
  81014. * Defines the location of the file to load
  81015. */
  81016. url,
  81017. /**
  81018. * Defines if mipmap should not be generated (default is false)
  81019. */
  81020. noMipmap,
  81021. /**
  81022. * Defines if texture must be inverted on Y axis (default is false)
  81023. */
  81024. invertY,
  81025. /**
  81026. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  81027. */
  81028. samplingMode) {
  81029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81030. var _this = _super.call(this, name) || this;
  81031. _this.name = name;
  81032. _this.url = url;
  81033. _this.noMipmap = noMipmap;
  81034. _this.invertY = invertY;
  81035. _this.samplingMode = samplingMode;
  81036. return _this;
  81037. }
  81038. /**
  81039. * Execute the current task
  81040. * @param scene defines the scene where you want your assets to be loaded
  81041. * @param onSuccess is a callback called when the task is successfully executed
  81042. * @param onError is a callback called if an error occurs
  81043. */
  81044. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81045. var onload = function () {
  81046. onSuccess();
  81047. };
  81048. var onerror = function (message, exception) {
  81049. onError(message, exception);
  81050. };
  81051. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  81052. };
  81053. return TextureAssetTask;
  81054. }(AbstractAssetTask));
  81055. BABYLON.TextureAssetTask = TextureAssetTask;
  81056. /**
  81057. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  81058. */
  81059. var CubeTextureAssetTask = /** @class */ (function (_super) {
  81060. __extends(CubeTextureAssetTask, _super);
  81061. /**
  81062. * Creates a new CubeTextureAssetTask
  81063. * @param name defines the name of the task
  81064. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81065. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81066. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81067. * @param files defines the explicit list of files (undefined by default)
  81068. */
  81069. function CubeTextureAssetTask(
  81070. /**
  81071. * Defines the name of the task
  81072. */
  81073. name,
  81074. /**
  81075. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  81076. */
  81077. url,
  81078. /**
  81079. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  81080. */
  81081. extensions,
  81082. /**
  81083. * Defines if mipmaps should not be generated (default is false)
  81084. */
  81085. noMipmap,
  81086. /**
  81087. * Defines the explicit list of files (undefined by default)
  81088. */
  81089. files) {
  81090. var _this = _super.call(this, name) || this;
  81091. _this.name = name;
  81092. _this.url = url;
  81093. _this.extensions = extensions;
  81094. _this.noMipmap = noMipmap;
  81095. _this.files = files;
  81096. return _this;
  81097. }
  81098. /**
  81099. * Execute the current task
  81100. * @param scene defines the scene where you want your assets to be loaded
  81101. * @param onSuccess is a callback called when the task is successfully executed
  81102. * @param onError is a callback called if an error occurs
  81103. */
  81104. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  81105. var onload = function () {
  81106. onSuccess();
  81107. };
  81108. var onerror = function (message, exception) {
  81109. onError(message, exception);
  81110. };
  81111. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  81112. };
  81113. return CubeTextureAssetTask;
  81114. }(AbstractAssetTask));
  81115. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  81116. /**
  81117. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  81118. */
  81119. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  81120. __extends(HDRCubeTextureAssetTask, _super);
  81121. /**
  81122. * Creates a new HDRCubeTextureAssetTask object
  81123. * @param name defines the name of the task
  81124. * @param url defines the location of the file to load
  81125. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  81126. * @param noMipmap defines if mipmaps should not be generated (default is false)
  81127. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81128. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  81129. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81130. */
  81131. function HDRCubeTextureAssetTask(
  81132. /**
  81133. * Defines the name of the task
  81134. */
  81135. name,
  81136. /**
  81137. * Defines the location of the file to load
  81138. */
  81139. url,
  81140. /**
  81141. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  81142. */
  81143. size,
  81144. /**
  81145. * Defines if mipmaps should not be generated (default is false)
  81146. */
  81147. noMipmap,
  81148. /**
  81149. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  81150. */
  81151. generateHarmonics,
  81152. /**
  81153. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  81154. */
  81155. useInGammaSpace,
  81156. /**
  81157. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  81158. */
  81159. usePMREMGenerator) {
  81160. if (noMipmap === void 0) { noMipmap = false; }
  81161. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81162. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81163. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81164. var _this = _super.call(this, name) || this;
  81165. _this.name = name;
  81166. _this.url = url;
  81167. _this.size = size;
  81168. _this.noMipmap = noMipmap;
  81169. _this.generateHarmonics = generateHarmonics;
  81170. _this.useInGammaSpace = useInGammaSpace;
  81171. _this.usePMREMGenerator = usePMREMGenerator;
  81172. return _this;
  81173. }
  81174. /**
  81175. * Execute the current task
  81176. * @param scene defines the scene where you want your assets to be loaded
  81177. * @param onSuccess is a callback called when the task is successfully executed
  81178. * @param onError is a callback called if an error occurs
  81179. */
  81180. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  81181. var onload = function () {
  81182. onSuccess();
  81183. };
  81184. var onerror = function (message, exception) {
  81185. onError(message, exception);
  81186. };
  81187. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  81188. };
  81189. return HDRCubeTextureAssetTask;
  81190. }(AbstractAssetTask));
  81191. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  81192. /**
  81193. * This class can be used to easily import assets into a scene
  81194. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  81195. */
  81196. var AssetsManager = /** @class */ (function () {
  81197. /**
  81198. * Creates a new AssetsManager
  81199. * @param scene defines the scene to work on
  81200. */
  81201. function AssetsManager(scene) {
  81202. this._isLoading = false;
  81203. this._tasks = new Array();
  81204. this._waitingTasksCount = 0;
  81205. this._totalTasksCount = 0;
  81206. /**
  81207. * Observable called when all tasks are processed
  81208. */
  81209. this.onTaskSuccessObservable = new BABYLON.Observable();
  81210. /**
  81211. * Observable called when a task had an error
  81212. */
  81213. this.onTaskErrorObservable = new BABYLON.Observable();
  81214. /**
  81215. * Observable called when a task is successful
  81216. */
  81217. this.onTasksDoneObservable = new BABYLON.Observable();
  81218. /**
  81219. * Observable called when a task is done (whatever the result is)
  81220. */
  81221. this.onProgressObservable = new BABYLON.Observable();
  81222. /**
  81223. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  81224. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  81225. */
  81226. this.useDefaultLoadingScreen = true;
  81227. this._scene = scene;
  81228. }
  81229. /**
  81230. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  81231. * @param taskName defines the name of the new task
  81232. * @param meshesNames defines the name of meshes to load
  81233. * @param rootUrl defines the root url to use to locate files
  81234. * @param sceneFilename defines the filename of the scene file
  81235. * @returns a new {BABYLON.MeshAssetTask} object
  81236. */
  81237. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  81238. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  81239. this._tasks.push(task);
  81240. return task;
  81241. };
  81242. /**
  81243. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  81244. * @param taskName defines the name of the new task
  81245. * @param url defines the url of the file to load
  81246. * @returns a new {BABYLON.TextFileAssetTask} object
  81247. */
  81248. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  81249. var task = new TextFileAssetTask(taskName, url);
  81250. this._tasks.push(task);
  81251. return task;
  81252. };
  81253. /**
  81254. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  81255. * @param taskName defines the name of the new task
  81256. * @param url defines the url of the file to load
  81257. * @returns a new {BABYLON.BinaryFileAssetTask} object
  81258. */
  81259. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  81260. var task = new BinaryFileAssetTask(taskName, url);
  81261. this._tasks.push(task);
  81262. return task;
  81263. };
  81264. /**
  81265. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  81266. * @param taskName defines the name of the new task
  81267. * @param url defines the url of the file to load
  81268. * @returns a new {BABYLON.ImageAssetTask} object
  81269. */
  81270. AssetsManager.prototype.addImageTask = function (taskName, url) {
  81271. var task = new ImageAssetTask(taskName, url);
  81272. this._tasks.push(task);
  81273. return task;
  81274. };
  81275. /**
  81276. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  81277. * @param taskName defines the name of the new task
  81278. * @param url defines the url of the file to load
  81279. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81280. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  81281. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  81282. * @returns a new {BABYLON.TextureAssetTask} object
  81283. */
  81284. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  81285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  81286. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  81287. this._tasks.push(task);
  81288. return task;
  81289. };
  81290. /**
  81291. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  81292. * @param taskName defines the name of the new task
  81293. * @param url defines the url of the file to load
  81294. * @param extensions defines the extension to use to load the cube map (can be null)
  81295. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81296. * @param files defines the list of files to load (can be null)
  81297. * @returns a new {BABYLON.CubeTextureAssetTask} object
  81298. */
  81299. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  81300. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  81301. this._tasks.push(task);
  81302. return task;
  81303. };
  81304. /**
  81305. *
  81306. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  81307. * @param taskName defines the name of the new task
  81308. * @param url defines the url of the file to load
  81309. * @param size defines the size you want for the cubemap (can be null)
  81310. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  81311. * @param generateHarmonics defines if you want to automatically generate (true by default)
  81312. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  81313. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  81314. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  81315. */
  81316. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  81317. if (noMipmap === void 0) { noMipmap = false; }
  81318. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81319. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  81320. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  81321. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  81322. this._tasks.push(task);
  81323. return task;
  81324. };
  81325. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  81326. var _this = this;
  81327. this._waitingTasksCount--;
  81328. try {
  81329. if (task.taskState === AssetTaskState.DONE) {
  81330. // Let's remove successfull tasks
  81331. BABYLON.Tools.SetImmediate(function () {
  81332. var index = _this._tasks.indexOf(task);
  81333. if (index > -1) {
  81334. _this._tasks.splice(index, 1);
  81335. }
  81336. });
  81337. }
  81338. if (this.onProgress) {
  81339. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  81340. }
  81341. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  81342. }
  81343. catch (e) {
  81344. BABYLON.Tools.Error("Error running progress callbacks.");
  81345. console.log(e);
  81346. }
  81347. if (this._waitingTasksCount === 0) {
  81348. try {
  81349. if (this.onFinish) {
  81350. this.onFinish(this._tasks);
  81351. }
  81352. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81353. }
  81354. catch (e) {
  81355. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  81356. console.log(e);
  81357. }
  81358. this._isLoading = false;
  81359. this._scene.getEngine().hideLoadingUI();
  81360. }
  81361. };
  81362. AssetsManager.prototype._runTask = function (task) {
  81363. var _this = this;
  81364. var done = function () {
  81365. try {
  81366. if (_this.onTaskSuccess) {
  81367. _this.onTaskSuccess(task);
  81368. }
  81369. _this.onTaskSuccessObservable.notifyObservers(task);
  81370. _this._decreaseWaitingTasksCount(task);
  81371. }
  81372. catch (e) {
  81373. error("Error executing task success callbacks", e);
  81374. }
  81375. };
  81376. var error = function (message, exception) {
  81377. task._setErrorObject(message, exception);
  81378. if (_this.onTaskError) {
  81379. _this.onTaskError(task);
  81380. }
  81381. _this.onTaskErrorObservable.notifyObservers(task);
  81382. _this._decreaseWaitingTasksCount(task);
  81383. };
  81384. task.run(this._scene, done, error);
  81385. };
  81386. /**
  81387. * Reset the {BABYLON.AssetsManager} and remove all tasks
  81388. * @return the current instance of the {BABYLON.AssetsManager}
  81389. */
  81390. AssetsManager.prototype.reset = function () {
  81391. this._isLoading = false;
  81392. this._tasks = new Array();
  81393. return this;
  81394. };
  81395. /**
  81396. * Start the loading process
  81397. * @return the current instance of the {BABYLON.AssetsManager}
  81398. */
  81399. AssetsManager.prototype.load = function () {
  81400. if (this._isLoading) {
  81401. return this;
  81402. }
  81403. this._isLoading = true;
  81404. this._waitingTasksCount = this._tasks.length;
  81405. this._totalTasksCount = this._tasks.length;
  81406. if (this._waitingTasksCount === 0) {
  81407. if (this.onFinish) {
  81408. this.onFinish(this._tasks);
  81409. }
  81410. this.onTasksDoneObservable.notifyObservers(this._tasks);
  81411. return this;
  81412. }
  81413. if (this.useDefaultLoadingScreen) {
  81414. this._scene.getEngine().displayLoadingUI();
  81415. }
  81416. for (var index = 0; index < this._tasks.length; index++) {
  81417. var task = this._tasks[index];
  81418. this._runTask(task);
  81419. }
  81420. return this;
  81421. };
  81422. return AssetsManager;
  81423. }());
  81424. BABYLON.AssetsManager = AssetsManager;
  81425. })(BABYLON || (BABYLON = {}));
  81426. //# sourceMappingURL=babylon.assetsManager.js.map
  81427. var BABYLON;
  81428. (function (BABYLON) {
  81429. var serializedGeometries = [];
  81430. var serializeGeometry = function (geometry, serializationGeometries) {
  81431. if (serializedGeometries[geometry.id]) {
  81432. return;
  81433. }
  81434. if (geometry.doNotSerialize) {
  81435. return;
  81436. }
  81437. if (geometry instanceof BABYLON.BoxGeometry) {
  81438. serializationGeometries.boxes.push(geometry.serialize());
  81439. }
  81440. else if (geometry instanceof BABYLON.SphereGeometry) {
  81441. serializationGeometries.spheres.push(geometry.serialize());
  81442. }
  81443. else if (geometry instanceof BABYLON.CylinderGeometry) {
  81444. serializationGeometries.cylinders.push(geometry.serialize());
  81445. }
  81446. else if (geometry instanceof BABYLON.TorusGeometry) {
  81447. serializationGeometries.toruses.push(geometry.serialize());
  81448. }
  81449. else if (geometry instanceof BABYLON.GroundGeometry) {
  81450. serializationGeometries.grounds.push(geometry.serialize());
  81451. }
  81452. else if (geometry instanceof BABYLON.Plane) {
  81453. serializationGeometries.planes.push(geometry.serialize());
  81454. }
  81455. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  81456. serializationGeometries.torusKnots.push(geometry.serialize());
  81457. }
  81458. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  81459. throw new Error("Unknown primitive type");
  81460. }
  81461. else {
  81462. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  81463. }
  81464. serializedGeometries[geometry.id] = true;
  81465. };
  81466. var serializeMesh = function (mesh, serializationScene) {
  81467. var serializationObject = {};
  81468. // Geometry
  81469. var geometry = mesh._geometry;
  81470. if (geometry) {
  81471. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  81472. // 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
  81473. serializeGeometry(geometry, serializationScene.geometries);
  81474. }
  81475. }
  81476. // Custom
  81477. if (mesh.serialize) {
  81478. mesh.serialize(serializationObject);
  81479. }
  81480. return serializationObject;
  81481. };
  81482. var finalizeSingleMesh = function (mesh, serializationObject) {
  81483. //only works if the mesh is already loaded
  81484. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81485. //serialize material
  81486. if (mesh.material) {
  81487. if (mesh.material instanceof BABYLON.StandardMaterial) {
  81488. serializationObject.materials = serializationObject.materials || [];
  81489. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81490. serializationObject.materials.push(mesh.material.serialize());
  81491. }
  81492. }
  81493. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  81494. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  81495. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  81496. serializationObject.multiMaterials.push(mesh.material.serialize());
  81497. }
  81498. }
  81499. }
  81500. //serialize geometry
  81501. var geometry = mesh._geometry;
  81502. if (geometry) {
  81503. if (!serializationObject.geometries) {
  81504. serializationObject.geometries = {};
  81505. serializationObject.geometries.boxes = [];
  81506. serializationObject.geometries.spheres = [];
  81507. serializationObject.geometries.cylinders = [];
  81508. serializationObject.geometries.toruses = [];
  81509. serializationObject.geometries.grounds = [];
  81510. serializationObject.geometries.planes = [];
  81511. serializationObject.geometries.torusKnots = [];
  81512. serializationObject.geometries.vertexData = [];
  81513. }
  81514. serializeGeometry(geometry, serializationObject.geometries);
  81515. }
  81516. // Skeletons
  81517. if (mesh.skeleton) {
  81518. serializationObject.skeletons = serializationObject.skeletons || [];
  81519. serializationObject.skeletons.push(mesh.skeleton.serialize());
  81520. }
  81521. //serialize the actual mesh
  81522. serializationObject.meshes = serializationObject.meshes || [];
  81523. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81524. }
  81525. };
  81526. var SceneSerializer = /** @class */ (function () {
  81527. function SceneSerializer() {
  81528. }
  81529. SceneSerializer.ClearCache = function () {
  81530. serializedGeometries = [];
  81531. };
  81532. SceneSerializer.Serialize = function (scene) {
  81533. var serializationObject = {};
  81534. SceneSerializer.ClearCache();
  81535. // Scene
  81536. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  81537. serializationObject.autoClear = scene.autoClear;
  81538. serializationObject.clearColor = scene.clearColor.asArray();
  81539. serializationObject.ambientColor = scene.ambientColor.asArray();
  81540. serializationObject.gravity = scene.gravity.asArray();
  81541. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  81542. serializationObject.workerCollisions = scene.workerCollisions;
  81543. // Fog
  81544. if (scene.fogMode && scene.fogMode !== 0) {
  81545. serializationObject.fogMode = scene.fogMode;
  81546. serializationObject.fogColor = scene.fogColor.asArray();
  81547. serializationObject.fogStart = scene.fogStart;
  81548. serializationObject.fogEnd = scene.fogEnd;
  81549. serializationObject.fogDensity = scene.fogDensity;
  81550. }
  81551. //Physics
  81552. if (scene.isPhysicsEnabled()) {
  81553. var physicEngine = scene.getPhysicsEngine();
  81554. if (physicEngine) {
  81555. serializationObject.physicsEnabled = true;
  81556. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  81557. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  81558. }
  81559. }
  81560. // Metadata
  81561. if (scene.metadata) {
  81562. serializationObject.metadata = scene.metadata;
  81563. }
  81564. // Morph targets
  81565. serializationObject.morphTargetManagers = [];
  81566. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  81567. var abstractMesh = _a[_i];
  81568. var manager = abstractMesh.morphTargetManager;
  81569. if (manager) {
  81570. serializationObject.morphTargetManagers.push(manager.serialize());
  81571. }
  81572. }
  81573. // Lights
  81574. serializationObject.lights = [];
  81575. var index;
  81576. var light;
  81577. for (index = 0; index < scene.lights.length; index++) {
  81578. light = scene.lights[index];
  81579. if (!light.doNotSerialize) {
  81580. serializationObject.lights.push(light.serialize());
  81581. }
  81582. }
  81583. // Cameras
  81584. serializationObject.cameras = [];
  81585. for (index = 0; index < scene.cameras.length; index++) {
  81586. var camera = scene.cameras[index];
  81587. if (!camera.doNotSerialize) {
  81588. serializationObject.cameras.push(camera.serialize());
  81589. }
  81590. }
  81591. if (scene.activeCamera) {
  81592. serializationObject.activeCameraID = scene.activeCamera.id;
  81593. }
  81594. // Animations
  81595. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  81596. // Materials
  81597. serializationObject.materials = [];
  81598. serializationObject.multiMaterials = [];
  81599. var material;
  81600. for (index = 0; index < scene.materials.length; index++) {
  81601. material = scene.materials[index];
  81602. if (!material.doNotSerialize) {
  81603. serializationObject.materials.push(material.serialize());
  81604. }
  81605. }
  81606. // MultiMaterials
  81607. serializationObject.multiMaterials = [];
  81608. for (index = 0; index < scene.multiMaterials.length; index++) {
  81609. var multiMaterial = scene.multiMaterials[index];
  81610. serializationObject.multiMaterials.push(multiMaterial.serialize());
  81611. }
  81612. // Environment texture
  81613. if (scene.environmentTexture) {
  81614. serializationObject.environmentTexture = scene.environmentTexture.name;
  81615. }
  81616. // Skeletons
  81617. serializationObject.skeletons = [];
  81618. for (index = 0; index < scene.skeletons.length; index++) {
  81619. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  81620. }
  81621. // Transform nodes
  81622. serializationObject.transformNodes = [];
  81623. for (index = 0; index < scene.transformNodes.length; index++) {
  81624. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  81625. }
  81626. // Geometries
  81627. serializationObject.geometries = {};
  81628. serializationObject.geometries.boxes = [];
  81629. serializationObject.geometries.spheres = [];
  81630. serializationObject.geometries.cylinders = [];
  81631. serializationObject.geometries.toruses = [];
  81632. serializationObject.geometries.grounds = [];
  81633. serializationObject.geometries.planes = [];
  81634. serializationObject.geometries.torusKnots = [];
  81635. serializationObject.geometries.vertexData = [];
  81636. serializedGeometries = [];
  81637. var geometries = scene.getGeometries();
  81638. for (index = 0; index < geometries.length; index++) {
  81639. var geometry = geometries[index];
  81640. if (geometry.isReady()) {
  81641. serializeGeometry(geometry, serializationObject.geometries);
  81642. }
  81643. }
  81644. // Meshes
  81645. serializationObject.meshes = [];
  81646. for (index = 0; index < scene.meshes.length; index++) {
  81647. var abstractMesh = scene.meshes[index];
  81648. if (abstractMesh instanceof BABYLON.Mesh) {
  81649. var mesh = abstractMesh;
  81650. if (!mesh.doNotSerialize) {
  81651. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81652. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81653. }
  81654. }
  81655. }
  81656. }
  81657. // Particles Systems
  81658. serializationObject.particleSystems = [];
  81659. for (index = 0; index < scene.particleSystems.length; index++) {
  81660. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  81661. }
  81662. // Lens flares
  81663. serializationObject.lensFlareSystems = [];
  81664. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  81665. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  81666. }
  81667. // Shadows
  81668. serializationObject.shadowGenerators = [];
  81669. for (index = 0; index < scene.lights.length; index++) {
  81670. light = scene.lights[index];
  81671. var shadowGenerator = light.getShadowGenerator();
  81672. if (shadowGenerator) {
  81673. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  81674. }
  81675. }
  81676. // Action Manager
  81677. if (scene.actionManager) {
  81678. serializationObject.actions = scene.actionManager.serialize("scene");
  81679. }
  81680. // Audio
  81681. serializationObject.sounds = [];
  81682. for (index = 0; index < scene.soundTracks.length; index++) {
  81683. var soundtrack = scene.soundTracks[index];
  81684. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  81685. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  81686. }
  81687. }
  81688. return serializationObject;
  81689. };
  81690. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  81691. if (withParents === void 0) { withParents = false; }
  81692. if (withChildren === void 0) { withChildren = false; }
  81693. var serializationObject = {};
  81694. SceneSerializer.ClearCache();
  81695. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  81696. if (withParents || withChildren) {
  81697. //deliberate for loop! not for each, appended should be processed as well.
  81698. for (var i = 0; i < toSerialize.length; ++i) {
  81699. if (withChildren) {
  81700. toSerialize[i].getDescendants().forEach(function (node) {
  81701. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  81702. toSerialize.push(node);
  81703. }
  81704. });
  81705. }
  81706. //make sure the array doesn't contain the object already
  81707. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  81708. toSerialize.push(toSerialize[i].parent);
  81709. }
  81710. }
  81711. }
  81712. toSerialize.forEach(function (mesh) {
  81713. finalizeSingleMesh(mesh, serializationObject);
  81714. });
  81715. return serializationObject;
  81716. };
  81717. return SceneSerializer;
  81718. }());
  81719. BABYLON.SceneSerializer = SceneSerializer;
  81720. })(BABYLON || (BABYLON = {}));
  81721. //# sourceMappingURL=babylon.sceneSerializer.js.map
  81722. var BABYLON;
  81723. (function (BABYLON) {
  81724. var ReflectionProbe = /** @class */ (function () {
  81725. function ReflectionProbe(name, size, scene, generateMipMaps) {
  81726. if (generateMipMaps === void 0) { generateMipMaps = true; }
  81727. var _this = this;
  81728. this.name = name;
  81729. this._viewMatrix = BABYLON.Matrix.Identity();
  81730. this._target = BABYLON.Vector3.Zero();
  81731. this._add = BABYLON.Vector3.Zero();
  81732. this.invertYAxis = false;
  81733. this.position = BABYLON.Vector3.Zero();
  81734. this._scene = scene;
  81735. this._scene.reflectionProbes.push(this);
  81736. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  81737. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  81738. switch (faceIndex) {
  81739. case 0:
  81740. _this._add.copyFromFloats(1, 0, 0);
  81741. break;
  81742. case 1:
  81743. _this._add.copyFromFloats(-1, 0, 0);
  81744. break;
  81745. case 2:
  81746. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  81747. break;
  81748. case 3:
  81749. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  81750. break;
  81751. case 4:
  81752. _this._add.copyFromFloats(0, 0, 1);
  81753. break;
  81754. case 5:
  81755. _this._add.copyFromFloats(0, 0, -1);
  81756. break;
  81757. }
  81758. if (_this._attachedMesh) {
  81759. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  81760. }
  81761. _this.position.addToRef(_this._add, _this._target);
  81762. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  81763. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  81764. scene._forcedViewPosition = _this.position;
  81765. });
  81766. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  81767. scene._forcedViewPosition = null;
  81768. scene.updateTransformMatrix(true);
  81769. });
  81770. if (scene.activeCamera) {
  81771. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  81772. }
  81773. }
  81774. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  81775. get: function () {
  81776. return this._renderTargetTexture.samples;
  81777. },
  81778. set: function (value) {
  81779. this._renderTargetTexture.samples = value;
  81780. },
  81781. enumerable: true,
  81782. configurable: true
  81783. });
  81784. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  81785. get: function () {
  81786. return this._renderTargetTexture.refreshRate;
  81787. },
  81788. set: function (value) {
  81789. this._renderTargetTexture.refreshRate = value;
  81790. },
  81791. enumerable: true,
  81792. configurable: true
  81793. });
  81794. ReflectionProbe.prototype.getScene = function () {
  81795. return this._scene;
  81796. };
  81797. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  81798. get: function () {
  81799. return this._renderTargetTexture;
  81800. },
  81801. enumerable: true,
  81802. configurable: true
  81803. });
  81804. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  81805. get: function () {
  81806. return this._renderTargetTexture.renderList;
  81807. },
  81808. enumerable: true,
  81809. configurable: true
  81810. });
  81811. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  81812. this._attachedMesh = mesh;
  81813. };
  81814. /**
  81815. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  81816. *
  81817. * @param renderingGroupId The rendering group id corresponding to its index
  81818. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  81819. */
  81820. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  81821. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  81822. };
  81823. ReflectionProbe.prototype.dispose = function () {
  81824. var index = this._scene.reflectionProbes.indexOf(this);
  81825. if (index !== -1) {
  81826. // Remove from the scene if found
  81827. this._scene.reflectionProbes.splice(index, 1);
  81828. }
  81829. if (this._renderTargetTexture) {
  81830. this._renderTargetTexture.dispose();
  81831. this._renderTargetTexture = null;
  81832. }
  81833. };
  81834. return ReflectionProbe;
  81835. }());
  81836. BABYLON.ReflectionProbe = ReflectionProbe;
  81837. })(BABYLON || (BABYLON = {}));
  81838. //# sourceMappingURL=babylon.reflectionProbe.js.map
  81839. var BABYLON;
  81840. (function (BABYLON) {
  81841. var Layer = /** @class */ (function () {
  81842. function Layer(name, imgUrl, scene, isBackground, color) {
  81843. this.name = name;
  81844. this.scale = new BABYLON.Vector2(1, 1);
  81845. this.offset = new BABYLON.Vector2(0, 0);
  81846. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  81847. this.layerMask = 0x0FFFFFFF;
  81848. this._vertexBuffers = {};
  81849. // Events
  81850. /**
  81851. * An event triggered when the layer is disposed.
  81852. * @type {BABYLON.Observable}
  81853. */
  81854. this.onDisposeObservable = new BABYLON.Observable();
  81855. /**
  81856. * An event triggered before rendering the scene
  81857. * @type {BABYLON.Observable}
  81858. */
  81859. this.onBeforeRenderObservable = new BABYLON.Observable();
  81860. /**
  81861. * An event triggered after rendering the scene
  81862. * @type {BABYLON.Observable}
  81863. */
  81864. this.onAfterRenderObservable = new BABYLON.Observable();
  81865. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  81866. this.isBackground = isBackground === undefined ? true : isBackground;
  81867. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  81868. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  81869. this._scene.layers.push(this);
  81870. var engine = this._scene.getEngine();
  81871. // VBO
  81872. var vertices = [];
  81873. vertices.push(1, 1);
  81874. vertices.push(-1, 1);
  81875. vertices.push(-1, -1);
  81876. vertices.push(1, -1);
  81877. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81878. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  81879. this._createIndexBuffer();
  81880. // Effects
  81881. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  81882. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  81883. }
  81884. Object.defineProperty(Layer.prototype, "onDispose", {
  81885. set: function (callback) {
  81886. if (this._onDisposeObserver) {
  81887. this.onDisposeObservable.remove(this._onDisposeObserver);
  81888. }
  81889. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  81890. },
  81891. enumerable: true,
  81892. configurable: true
  81893. });
  81894. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  81895. set: function (callback) {
  81896. if (this._onBeforeRenderObserver) {
  81897. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  81898. }
  81899. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  81900. },
  81901. enumerable: true,
  81902. configurable: true
  81903. });
  81904. Object.defineProperty(Layer.prototype, "onAfterRender", {
  81905. set: function (callback) {
  81906. if (this._onAfterRenderObserver) {
  81907. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  81908. }
  81909. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  81910. },
  81911. enumerable: true,
  81912. configurable: true
  81913. });
  81914. Layer.prototype._createIndexBuffer = function () {
  81915. var engine = this._scene.getEngine();
  81916. // Indices
  81917. var indices = [];
  81918. indices.push(0);
  81919. indices.push(1);
  81920. indices.push(2);
  81921. indices.push(0);
  81922. indices.push(2);
  81923. indices.push(3);
  81924. this._indexBuffer = engine.createIndexBuffer(indices);
  81925. };
  81926. Layer.prototype._rebuild = function () {
  81927. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81928. if (vb) {
  81929. vb._rebuild();
  81930. }
  81931. this._createIndexBuffer();
  81932. };
  81933. Layer.prototype.render = function () {
  81934. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  81935. // Check
  81936. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  81937. return;
  81938. var engine = this._scene.getEngine();
  81939. this.onBeforeRenderObservable.notifyObservers(this);
  81940. // Render
  81941. engine.enableEffect(currentEffect);
  81942. engine.setState(false);
  81943. // Texture
  81944. currentEffect.setTexture("textureSampler", this.texture);
  81945. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  81946. // Color
  81947. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  81948. // Scale / offset
  81949. currentEffect.setVector2("offset", this.offset);
  81950. currentEffect.setVector2("scale", this.scale);
  81951. // VBOs
  81952. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  81953. // Draw order
  81954. if (!this.alphaTest) {
  81955. engine.setAlphaMode(this.alphaBlendingMode);
  81956. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81957. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81958. }
  81959. else {
  81960. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81961. }
  81962. this.onAfterRenderObservable.notifyObservers(this);
  81963. };
  81964. Layer.prototype.dispose = function () {
  81965. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81966. if (vertexBuffer) {
  81967. vertexBuffer.dispose();
  81968. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81969. }
  81970. if (this._indexBuffer) {
  81971. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81972. this._indexBuffer = null;
  81973. }
  81974. if (this.texture) {
  81975. this.texture.dispose();
  81976. this.texture = null;
  81977. }
  81978. // Remove from scene
  81979. var index = this._scene.layers.indexOf(this);
  81980. this._scene.layers.splice(index, 1);
  81981. // Callback
  81982. this.onDisposeObservable.notifyObservers(this);
  81983. this.onDisposeObservable.clear();
  81984. this.onAfterRenderObservable.clear();
  81985. this.onBeforeRenderObservable.clear();
  81986. };
  81987. return Layer;
  81988. }());
  81989. BABYLON.Layer = Layer;
  81990. })(BABYLON || (BABYLON = {}));
  81991. //# sourceMappingURL=babylon.layer.js.map
  81992. var BABYLON;
  81993. (function (BABYLON) {
  81994. var TextureTools = /** @class */ (function () {
  81995. function TextureTools() {
  81996. }
  81997. /**
  81998. * Uses the GPU to create a copy texture rescaled at a given size
  81999. * @param texture Texture to copy from
  82000. * @param width Desired width
  82001. * @param height Desired height
  82002. * @return Generated texture
  82003. */
  82004. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  82005. if (useBilinearMode === void 0) { useBilinearMode = true; }
  82006. var scene = texture.getScene();
  82007. var engine = scene.getEngine();
  82008. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  82009. rtt.wrapU = texture.wrapU;
  82010. rtt.wrapV = texture.wrapV;
  82011. rtt.uOffset = texture.uOffset;
  82012. rtt.vOffset = texture.vOffset;
  82013. rtt.uScale = texture.uScale;
  82014. rtt.vScale = texture.vScale;
  82015. rtt.uAng = texture.uAng;
  82016. rtt.vAng = texture.vAng;
  82017. rtt.wAng = texture.wAng;
  82018. rtt.coordinatesIndex = texture.coordinatesIndex;
  82019. rtt.level = texture.level;
  82020. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  82021. rtt._texture.isReady = false;
  82022. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82023. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82024. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82025. passPostProcess.getEffect().executeWhenCompiled(function () {
  82026. passPostProcess.onApply = function (effect) {
  82027. effect.setTexture("textureSampler", texture);
  82028. };
  82029. var internalTexture = rtt.getInternalTexture();
  82030. if (internalTexture) {
  82031. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  82032. engine.unBindFramebuffer(internalTexture);
  82033. rtt.disposeFramebufferObjects();
  82034. passPostProcess.dispose();
  82035. internalTexture.isReady = true;
  82036. }
  82037. });
  82038. return rtt;
  82039. };
  82040. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  82041. if (!scene._environmentBRDFTexture) {
  82042. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82043. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82044. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82045. scene._environmentBRDFTexture = texture;
  82046. }
  82047. return scene._environmentBRDFTexture;
  82048. };
  82049. 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=";
  82050. return TextureTools;
  82051. }());
  82052. BABYLON.TextureTools = TextureTools;
  82053. })(BABYLON || (BABYLON = {}));
  82054. //# sourceMappingURL=babylon.textureTools.js.map
  82055. var BABYLON;
  82056. (function (BABYLON) {
  82057. var FramingBehavior = /** @class */ (function () {
  82058. function FramingBehavior() {
  82059. this._mode = FramingBehavior.FitFrustumSidesMode;
  82060. this._radiusScale = 1.0;
  82061. this._positionScale = 0.5;
  82062. this._defaultElevation = 0.3;
  82063. this._elevationReturnTime = 1500;
  82064. this._elevationReturnWaitTime = 1000;
  82065. this._zoomStopsAnimation = false;
  82066. this._framingTime = 1500;
  82067. this._isPointerDown = false;
  82068. this._lastInteractionTime = -Infinity;
  82069. // Framing control
  82070. this._animatables = new Array();
  82071. this._betaIsAnimating = false;
  82072. }
  82073. Object.defineProperty(FramingBehavior.prototype, "name", {
  82074. get: function () {
  82075. return "Framing";
  82076. },
  82077. enumerable: true,
  82078. configurable: true
  82079. });
  82080. Object.defineProperty(FramingBehavior.prototype, "mode", {
  82081. /**
  82082. * Gets current mode used by the behavior.
  82083. */
  82084. get: function () {
  82085. return this._mode;
  82086. },
  82087. /**
  82088. * Sets the current mode used by the behavior
  82089. */
  82090. set: function (mode) {
  82091. this._mode = mode;
  82092. },
  82093. enumerable: true,
  82094. configurable: true
  82095. });
  82096. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  82097. /**
  82098. * Gets the scale applied to the radius
  82099. */
  82100. get: function () {
  82101. return this._radiusScale;
  82102. },
  82103. /**
  82104. * Sets the scale applied to the radius (1 by default)
  82105. */
  82106. set: function (radius) {
  82107. this._radiusScale = radius;
  82108. },
  82109. enumerable: true,
  82110. configurable: true
  82111. });
  82112. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  82113. /**
  82114. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82115. */
  82116. get: function () {
  82117. return this._positionScale;
  82118. },
  82119. /**
  82120. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  82121. */
  82122. set: function (scale) {
  82123. this._positionScale = scale;
  82124. },
  82125. enumerable: true,
  82126. configurable: true
  82127. });
  82128. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  82129. /**
  82130. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82131. * behaviour is triggered, in radians.
  82132. */
  82133. get: function () {
  82134. return this._defaultElevation;
  82135. },
  82136. /**
  82137. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  82138. * behaviour is triggered, in radians.
  82139. */
  82140. set: function (elevation) {
  82141. this._defaultElevation = elevation;
  82142. },
  82143. enumerable: true,
  82144. configurable: true
  82145. });
  82146. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  82147. /**
  82148. * Gets the time (in milliseconds) taken to return to the default beta position.
  82149. * Negative value indicates camera should not return to default.
  82150. */
  82151. get: function () {
  82152. return this._elevationReturnTime;
  82153. },
  82154. /**
  82155. * Sets the time (in milliseconds) taken to return to the default beta position.
  82156. * Negative value indicates camera should not return to default.
  82157. */
  82158. set: function (speed) {
  82159. this._elevationReturnTime = speed;
  82160. },
  82161. enumerable: true,
  82162. configurable: true
  82163. });
  82164. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  82165. /**
  82166. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82167. */
  82168. get: function () {
  82169. return this._elevationReturnWaitTime;
  82170. },
  82171. /**
  82172. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  82173. */
  82174. set: function (time) {
  82175. this._elevationReturnWaitTime = time;
  82176. },
  82177. enumerable: true,
  82178. configurable: true
  82179. });
  82180. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  82181. /**
  82182. * Gets the flag that indicates if user zooming should stop animation.
  82183. */
  82184. get: function () {
  82185. return this._zoomStopsAnimation;
  82186. },
  82187. /**
  82188. * Sets the flag that indicates if user zooming should stop animation.
  82189. */
  82190. set: function (flag) {
  82191. this._zoomStopsAnimation = flag;
  82192. },
  82193. enumerable: true,
  82194. configurable: true
  82195. });
  82196. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  82197. /**
  82198. * Gets the transition time when framing the mesh, in milliseconds
  82199. */
  82200. get: function () {
  82201. return this._framingTime;
  82202. },
  82203. /**
  82204. * Sets the transition time when framing the mesh, in milliseconds
  82205. */
  82206. set: function (time) {
  82207. this._framingTime = time;
  82208. },
  82209. enumerable: true,
  82210. configurable: true
  82211. });
  82212. FramingBehavior.prototype.init = function () {
  82213. // Do notihng
  82214. };
  82215. FramingBehavior.prototype.attach = function (camera) {
  82216. var _this = this;
  82217. this._attachedCamera = camera;
  82218. var scene = this._attachedCamera.getScene();
  82219. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  82220. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82221. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82222. _this._isPointerDown = true;
  82223. return;
  82224. }
  82225. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82226. _this._isPointerDown = false;
  82227. }
  82228. });
  82229. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82230. if (mesh) {
  82231. _this.zoomOnMesh(mesh);
  82232. }
  82233. });
  82234. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82235. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82236. _this._applyUserInteraction();
  82237. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  82238. // back to the default position after a given timeout
  82239. _this._maintainCameraAboveGround();
  82240. });
  82241. };
  82242. FramingBehavior.prototype.detach = function () {
  82243. if (!this._attachedCamera) {
  82244. return;
  82245. }
  82246. var scene = this._attachedCamera.getScene();
  82247. if (this._onPrePointerObservableObserver) {
  82248. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82249. }
  82250. if (this._onAfterCheckInputsObserver) {
  82251. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82252. }
  82253. if (this._onMeshTargetChangedObserver) {
  82254. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82255. }
  82256. this._attachedCamera = null;
  82257. };
  82258. /**
  82259. * Targets the given mesh and updates zoom level accordingly.
  82260. * @param mesh The mesh to target.
  82261. * @param radius Optional. If a cached radius position already exists, overrides default.
  82262. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82263. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82264. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82265. */
  82266. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82267. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82268. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82269. mesh.computeWorldMatrix(true);
  82270. var boundingBox = mesh.getBoundingInfo().boundingBox;
  82271. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  82272. };
  82273. /**
  82274. * Targets the given mesh with its children and updates zoom level accordingly.
  82275. * @param mesh The mesh to target.
  82276. * @param radius Optional. If a cached radius position already exists, overrides default.
  82277. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82278. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82279. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82280. */
  82281. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  82282. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82283. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82284. mesh.computeWorldMatrix(true);
  82285. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  82286. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  82287. };
  82288. /**
  82289. * Targets the given meshes with their children and updates zoom level accordingly.
  82290. * @param meshes The mesh to target.
  82291. * @param radius Optional. If a cached radius position already exists, overrides default.
  82292. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82293. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82294. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82295. */
  82296. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  82297. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82298. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82299. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  82300. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  82301. for (var i = 0; i < meshes.length; i++) {
  82302. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  82303. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  82304. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  82305. }
  82306. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  82307. };
  82308. /**
  82309. * Targets the given mesh and updates zoom level accordingly.
  82310. * @param mesh The mesh to target.
  82311. * @param radius Optional. If a cached radius position already exists, overrides default.
  82312. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  82313. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  82314. * @param onAnimationEnd Callback triggered at the end of the framing animation
  82315. */
  82316. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  82317. var _this = this;
  82318. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  82319. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  82320. var zoomTarget;
  82321. if (!this._attachedCamera) {
  82322. return;
  82323. }
  82324. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  82325. var bottom = minimumWorld.y;
  82326. var top = maximumWorld.y;
  82327. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  82328. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  82329. if (focusOnOriginXZ) {
  82330. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  82331. }
  82332. else {
  82333. var centerWorld = minimumWorld.add(radiusWorld);
  82334. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  82335. }
  82336. if (!this._vectorTransition) {
  82337. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  82338. }
  82339. this._betaIsAnimating = true;
  82340. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  82341. if (animatable) {
  82342. this._animatables.push(animatable);
  82343. }
  82344. // sets the radius and lower radius bounds
  82345. // Small delta ensures camera is not always at lower zoom limit.
  82346. var radius = 0;
  82347. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  82348. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82349. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  82350. radius = position;
  82351. }
  82352. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82353. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  82354. if (this._attachedCamera.lowerRadiusLimit === null) {
  82355. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  82356. }
  82357. }
  82358. // Set sensibilities
  82359. var extend = maximumWorld.subtract(minimumWorld).length();
  82360. this._attachedCamera.panningSensibility = 5000 / extend;
  82361. this._attachedCamera.wheelPrecision = 100 / radius;
  82362. // transition to new radius
  82363. if (!this._radiusTransition) {
  82364. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82365. }
  82366. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  82367. if (onAnimationEnd) {
  82368. onAnimationEnd();
  82369. }
  82370. if (_this._attachedCamera) {
  82371. _this._attachedCamera.storeState();
  82372. }
  82373. });
  82374. if (animatable) {
  82375. this._animatables.push(animatable);
  82376. }
  82377. };
  82378. /**
  82379. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  82380. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  82381. * frustum width.
  82382. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  82383. * to fully enclose the mesh in the viewing frustum.
  82384. */
  82385. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  82386. var size = maximumWorld.subtract(minimumWorld);
  82387. var boxVectorGlobalDiagonal = size.length();
  82388. var frustumSlope = this._getFrustumSlope();
  82389. // Formula for setting distance
  82390. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  82391. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  82392. // Horizon distance
  82393. var radius = radiusWithoutFraming * this._radiusScale;
  82394. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  82395. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  82396. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  82397. var camera = this._attachedCamera;
  82398. if (!camera) {
  82399. return 0;
  82400. }
  82401. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  82402. // Don't exceed the requested limit
  82403. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  82404. }
  82405. // Don't exceed the upper radius limit
  82406. if (camera.upperRadiusLimit) {
  82407. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  82408. }
  82409. return distance;
  82410. };
  82411. /**
  82412. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  82413. * is automatically returned to its default position (expected to be above ground plane).
  82414. */
  82415. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  82416. var _this = this;
  82417. if (this._elevationReturnTime < 0) {
  82418. return;
  82419. }
  82420. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  82421. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  82422. var limitBeta = Math.PI * 0.5;
  82423. // Bring the camera back up if below the ground plane
  82424. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  82425. this._betaIsAnimating = true;
  82426. //Transition to new position
  82427. this.stopAllAnimations();
  82428. if (!this._betaTransition) {
  82429. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  82430. }
  82431. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  82432. _this._clearAnimationLocks();
  82433. _this.stopAllAnimations();
  82434. });
  82435. if (animatabe) {
  82436. this._animatables.push(animatabe);
  82437. }
  82438. }
  82439. };
  82440. /**
  82441. * Returns the frustum slope based on the canvas ratio and camera FOV
  82442. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  82443. */
  82444. FramingBehavior.prototype._getFrustumSlope = function () {
  82445. // Calculate the viewport ratio
  82446. // Aspect Ratio is Height/Width.
  82447. var camera = this._attachedCamera;
  82448. if (!camera) {
  82449. return BABYLON.Vector2.Zero();
  82450. }
  82451. var engine = camera.getScene().getEngine();
  82452. var aspectRatio = engine.getAspectRatio(camera);
  82453. // Camera FOV is the vertical field of view (top-bottom) in radians.
  82454. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  82455. var frustumSlopeY = Math.tan(camera.fov / 2);
  82456. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  82457. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  82458. // along the forward vector.
  82459. var frustumSlopeX = frustumSlopeY * aspectRatio;
  82460. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  82461. };
  82462. /**
  82463. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  82464. */
  82465. FramingBehavior.prototype._clearAnimationLocks = function () {
  82466. this._betaIsAnimating = false;
  82467. };
  82468. /**
  82469. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82470. */
  82471. FramingBehavior.prototype._applyUserInteraction = function () {
  82472. if (this.isUserIsMoving) {
  82473. this._lastInteractionTime = BABYLON.Tools.Now;
  82474. this.stopAllAnimations();
  82475. this._clearAnimationLocks();
  82476. }
  82477. };
  82478. /**
  82479. * Stops and removes all animations that have been applied to the camera
  82480. */
  82481. FramingBehavior.prototype.stopAllAnimations = function () {
  82482. if (this._attachedCamera) {
  82483. this._attachedCamera.animations = [];
  82484. }
  82485. while (this._animatables.length) {
  82486. if (this._animatables[0]) {
  82487. this._animatables[0].onAnimationEnd = null;
  82488. this._animatables[0].stop();
  82489. }
  82490. this._animatables.shift();
  82491. }
  82492. };
  82493. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  82494. /**
  82495. * Gets a value indicating if the user is moving the camera
  82496. */
  82497. get: function () {
  82498. if (!this._attachedCamera) {
  82499. return false;
  82500. }
  82501. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82502. this._attachedCamera.inertialBetaOffset !== 0 ||
  82503. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82504. this._attachedCamera.inertialPanningX !== 0 ||
  82505. this._attachedCamera.inertialPanningY !== 0 ||
  82506. this._isPointerDown;
  82507. },
  82508. enumerable: true,
  82509. configurable: true
  82510. });
  82511. /**
  82512. * The easing function used by animations
  82513. */
  82514. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  82515. /**
  82516. * The easing mode used by animations
  82517. */
  82518. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  82519. // Statics
  82520. /**
  82521. * The camera can move all the way towards the mesh.
  82522. */
  82523. FramingBehavior.IgnoreBoundsSizeMode = 0;
  82524. /**
  82525. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  82526. */
  82527. FramingBehavior.FitFrustumSidesMode = 1;
  82528. return FramingBehavior;
  82529. }());
  82530. BABYLON.FramingBehavior = FramingBehavior;
  82531. })(BABYLON || (BABYLON = {}));
  82532. //# sourceMappingURL=babylon.framingBehavior.js.map
  82533. var BABYLON;
  82534. (function (BABYLON) {
  82535. /**
  82536. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  82537. */
  82538. var BouncingBehavior = /** @class */ (function () {
  82539. function BouncingBehavior() {
  82540. /**
  82541. * The duration of the animation, in milliseconds
  82542. */
  82543. this.transitionDuration = 450;
  82544. /**
  82545. * Length of the distance animated by the transition when lower radius is reached
  82546. */
  82547. this.lowerRadiusTransitionRange = 2;
  82548. /**
  82549. * Length of the distance animated by the transition when upper radius is reached
  82550. */
  82551. this.upperRadiusTransitionRange = -2;
  82552. this._autoTransitionRange = false;
  82553. // Animations
  82554. this._radiusIsAnimating = false;
  82555. this._radiusBounceTransition = null;
  82556. this._animatables = new Array();
  82557. }
  82558. Object.defineProperty(BouncingBehavior.prototype, "name", {
  82559. get: function () {
  82560. return "Bouncing";
  82561. },
  82562. enumerable: true,
  82563. configurable: true
  82564. });
  82565. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  82566. /**
  82567. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82568. */
  82569. get: function () {
  82570. return this._autoTransitionRange;
  82571. },
  82572. /**
  82573. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  82574. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  82575. */
  82576. set: function (value) {
  82577. var _this = this;
  82578. if (this._autoTransitionRange === value) {
  82579. return;
  82580. }
  82581. this._autoTransitionRange = value;
  82582. var camera = this._attachedCamera;
  82583. if (!camera) {
  82584. return;
  82585. }
  82586. if (value) {
  82587. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  82588. if (!mesh) {
  82589. return;
  82590. }
  82591. mesh.computeWorldMatrix(true);
  82592. var diagonal = mesh.getBoundingInfo().diagonalLength;
  82593. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  82594. _this.upperRadiusTransitionRange = diagonal * 0.05;
  82595. });
  82596. }
  82597. else if (this._onMeshTargetChangedObserver) {
  82598. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82599. }
  82600. },
  82601. enumerable: true,
  82602. configurable: true
  82603. });
  82604. BouncingBehavior.prototype.init = function () {
  82605. // Do notihng
  82606. };
  82607. BouncingBehavior.prototype.attach = function (camera) {
  82608. var _this = this;
  82609. this._attachedCamera = camera;
  82610. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82611. if (!_this._attachedCamera) {
  82612. return;
  82613. }
  82614. // Add the bounce animation to the lower radius limit
  82615. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  82616. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  82617. }
  82618. // Add the bounce animation to the upper radius limit
  82619. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  82620. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  82621. }
  82622. });
  82623. };
  82624. BouncingBehavior.prototype.detach = function () {
  82625. if (!this._attachedCamera) {
  82626. return;
  82627. }
  82628. if (this._onAfterCheckInputsObserver) {
  82629. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82630. }
  82631. if (this._onMeshTargetChangedObserver) {
  82632. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82633. }
  82634. this._attachedCamera = null;
  82635. };
  82636. /**
  82637. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  82638. * @param radiusLimit The limit to check against.
  82639. * @return Bool to indicate if at limit.
  82640. */
  82641. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  82642. if (!this._attachedCamera) {
  82643. return false;
  82644. }
  82645. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  82646. return true;
  82647. }
  82648. return false;
  82649. };
  82650. /**
  82651. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  82652. * @param radiusDelta The delta by which to animate to. Can be negative.
  82653. */
  82654. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  82655. var _this = this;
  82656. if (!this._attachedCamera) {
  82657. return;
  82658. }
  82659. if (!this._radiusBounceTransition) {
  82660. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  82661. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  82662. }
  82663. // Prevent zoom until bounce has completed
  82664. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  82665. this._attachedCamera.wheelPrecision = Infinity;
  82666. this._attachedCamera.inertialRadiusOffset = 0;
  82667. // Animate to the radius limit
  82668. this.stopAllAnimations();
  82669. this._radiusIsAnimating = true;
  82670. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  82671. if (animatable) {
  82672. this._animatables.push(animatable);
  82673. }
  82674. };
  82675. /**
  82676. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  82677. */
  82678. BouncingBehavior.prototype._clearAnimationLocks = function () {
  82679. this._radiusIsAnimating = false;
  82680. if (this._attachedCamera) {
  82681. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  82682. }
  82683. };
  82684. /**
  82685. * Stops and removes all animations that have been applied to the camera
  82686. */
  82687. BouncingBehavior.prototype.stopAllAnimations = function () {
  82688. if (this._attachedCamera) {
  82689. this._attachedCamera.animations = [];
  82690. }
  82691. while (this._animatables.length) {
  82692. this._animatables[0].onAnimationEnd = null;
  82693. this._animatables[0].stop();
  82694. this._animatables.shift();
  82695. }
  82696. };
  82697. /**
  82698. * The easing function used by animations
  82699. */
  82700. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  82701. /**
  82702. * The easing mode used by animations
  82703. */
  82704. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  82705. return BouncingBehavior;
  82706. }());
  82707. BABYLON.BouncingBehavior = BouncingBehavior;
  82708. })(BABYLON || (BABYLON = {}));
  82709. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  82710. var BABYLON;
  82711. (function (BABYLON) {
  82712. var AutoRotationBehavior = /** @class */ (function () {
  82713. function AutoRotationBehavior() {
  82714. this._zoomStopsAnimation = false;
  82715. this._idleRotationSpeed = 0.05;
  82716. this._idleRotationWaitTime = 2000;
  82717. this._idleRotationSpinupTime = 2000;
  82718. this._isPointerDown = false;
  82719. this._lastFrameTime = null;
  82720. this._lastInteractionTime = -Infinity;
  82721. this._cameraRotationSpeed = 0;
  82722. this._lastFrameRadius = 0;
  82723. }
  82724. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  82725. get: function () {
  82726. return "AutoRotation";
  82727. },
  82728. enumerable: true,
  82729. configurable: true
  82730. });
  82731. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  82732. /**
  82733. * Gets the flag that indicates if user zooming should stop animation.
  82734. */
  82735. get: function () {
  82736. return this._zoomStopsAnimation;
  82737. },
  82738. /**
  82739. * Sets the flag that indicates if user zooming should stop animation.
  82740. */
  82741. set: function (flag) {
  82742. this._zoomStopsAnimation = flag;
  82743. },
  82744. enumerable: true,
  82745. configurable: true
  82746. });
  82747. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  82748. /**
  82749. * Gets the default speed at which the camera rotates around the model.
  82750. */
  82751. get: function () {
  82752. return this._idleRotationSpeed;
  82753. },
  82754. /**
  82755. * Sets the default speed at which the camera rotates around the model.
  82756. */
  82757. set: function (speed) {
  82758. this._idleRotationSpeed = speed;
  82759. },
  82760. enumerable: true,
  82761. configurable: true
  82762. });
  82763. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  82764. /**
  82765. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  82766. */
  82767. get: function () {
  82768. return this._idleRotationWaitTime;
  82769. },
  82770. /**
  82771. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  82772. */
  82773. set: function (time) {
  82774. this._idleRotationWaitTime = time;
  82775. },
  82776. enumerable: true,
  82777. configurable: true
  82778. });
  82779. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  82780. /**
  82781. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  82782. */
  82783. get: function () {
  82784. return this._idleRotationSpinupTime;
  82785. },
  82786. /**
  82787. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  82788. */
  82789. set: function (time) {
  82790. this._idleRotationSpinupTime = time;
  82791. },
  82792. enumerable: true,
  82793. configurable: true
  82794. });
  82795. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  82796. /**
  82797. * Gets a value indicating if the camera is currently rotating because of this behavior
  82798. */
  82799. get: function () {
  82800. return Math.abs(this._cameraRotationSpeed) > 0;
  82801. },
  82802. enumerable: true,
  82803. configurable: true
  82804. });
  82805. AutoRotationBehavior.prototype.init = function () {
  82806. // Do notihng
  82807. };
  82808. AutoRotationBehavior.prototype.attach = function (camera) {
  82809. var _this = this;
  82810. this._attachedCamera = camera;
  82811. var scene = this._attachedCamera.getScene();
  82812. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82813. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82814. _this._isPointerDown = true;
  82815. return;
  82816. }
  82817. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82818. _this._isPointerDown = false;
  82819. }
  82820. });
  82821. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82822. var now = BABYLON.Tools.Now;
  82823. var dt = 0;
  82824. if (_this._lastFrameTime != null) {
  82825. dt = now - _this._lastFrameTime;
  82826. }
  82827. _this._lastFrameTime = now;
  82828. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82829. _this._applyUserInteraction();
  82830. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  82831. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  82832. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  82833. // Step camera rotation by rotation speed
  82834. if (_this._attachedCamera) {
  82835. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  82836. }
  82837. });
  82838. };
  82839. AutoRotationBehavior.prototype.detach = function () {
  82840. if (!this._attachedCamera) {
  82841. return;
  82842. }
  82843. var scene = this._attachedCamera.getScene();
  82844. if (this._onPrePointerObservableObserver) {
  82845. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82846. }
  82847. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82848. this._attachedCamera = null;
  82849. };
  82850. /**
  82851. * Returns true if user is scrolling.
  82852. * @return true if user is scrolling.
  82853. */
  82854. AutoRotationBehavior.prototype._userIsZooming = function () {
  82855. if (!this._attachedCamera) {
  82856. return false;
  82857. }
  82858. return this._attachedCamera.inertialRadiusOffset !== 0;
  82859. };
  82860. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  82861. if (!this._attachedCamera) {
  82862. return false;
  82863. }
  82864. var zoomHasHitLimit = false;
  82865. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  82866. zoomHasHitLimit = true;
  82867. }
  82868. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  82869. this._lastFrameRadius = this._attachedCamera.radius;
  82870. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  82871. };
  82872. /**
  82873. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82874. */
  82875. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  82876. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  82877. this._lastInteractionTime = BABYLON.Tools.Now;
  82878. }
  82879. };
  82880. // Tools
  82881. AutoRotationBehavior.prototype._userIsMoving = function () {
  82882. if (!this._attachedCamera) {
  82883. return false;
  82884. }
  82885. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82886. this._attachedCamera.inertialBetaOffset !== 0 ||
  82887. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82888. this._attachedCamera.inertialPanningX !== 0 ||
  82889. this._attachedCamera.inertialPanningY !== 0 ||
  82890. this._isPointerDown;
  82891. };
  82892. return AutoRotationBehavior;
  82893. }());
  82894. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  82895. })(BABYLON || (BABYLON = {}));
  82896. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  82897. var BABYLON;
  82898. (function (BABYLON) {
  82899. /**
  82900. * This class can be used to get instrumentation data from a Babylon engine
  82901. */
  82902. var EngineInstrumentation = /** @class */ (function () {
  82903. function EngineInstrumentation(engine) {
  82904. this.engine = engine;
  82905. this._captureGPUFrameTime = false;
  82906. this._gpuFrameTime = new BABYLON.PerfCounter();
  82907. this._captureShaderCompilationTime = false;
  82908. this._shaderCompilationTime = new BABYLON.PerfCounter();
  82909. // Observers
  82910. this._onBeginFrameObserver = null;
  82911. this._onEndFrameObserver = null;
  82912. this._onBeforeShaderCompilationObserver = null;
  82913. this._onAfterShaderCompilationObserver = null;
  82914. }
  82915. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  82916. // Properties
  82917. /**
  82918. * Gets the perf counter used for GPU frame time
  82919. */
  82920. get: function () {
  82921. return this._gpuFrameTime;
  82922. },
  82923. enumerable: true,
  82924. configurable: true
  82925. });
  82926. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  82927. /**
  82928. * Gets the GPU frame time capture status
  82929. */
  82930. get: function () {
  82931. return this._captureGPUFrameTime;
  82932. },
  82933. /**
  82934. * Enable or disable the GPU frame time capture
  82935. */
  82936. set: function (value) {
  82937. var _this = this;
  82938. if (value === this._captureGPUFrameTime) {
  82939. return;
  82940. }
  82941. this._captureGPUFrameTime = value;
  82942. if (value) {
  82943. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  82944. if (!_this._gpuFrameTimeToken) {
  82945. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  82946. }
  82947. });
  82948. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  82949. if (!_this._gpuFrameTimeToken) {
  82950. return;
  82951. }
  82952. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  82953. if (time > -1) {
  82954. _this._gpuFrameTimeToken = null;
  82955. _this._gpuFrameTime.fetchNewFrame();
  82956. _this._gpuFrameTime.addCount(time, true);
  82957. }
  82958. });
  82959. }
  82960. else {
  82961. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82962. this._onBeginFrameObserver = null;
  82963. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82964. this._onEndFrameObserver = null;
  82965. }
  82966. },
  82967. enumerable: true,
  82968. configurable: true
  82969. });
  82970. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  82971. /**
  82972. * Gets the perf counter used for shader compilation time
  82973. */
  82974. get: function () {
  82975. return this._shaderCompilationTime;
  82976. },
  82977. enumerable: true,
  82978. configurable: true
  82979. });
  82980. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  82981. /**
  82982. * Gets the shader compilation time capture status
  82983. */
  82984. get: function () {
  82985. return this._captureShaderCompilationTime;
  82986. },
  82987. /**
  82988. * Enable or disable the shader compilation time capture
  82989. */
  82990. set: function (value) {
  82991. var _this = this;
  82992. if (value === this._captureShaderCompilationTime) {
  82993. return;
  82994. }
  82995. this._captureShaderCompilationTime = value;
  82996. if (value) {
  82997. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  82998. _this._shaderCompilationTime.fetchNewFrame();
  82999. _this._shaderCompilationTime.beginMonitoring();
  83000. });
  83001. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  83002. _this._shaderCompilationTime.endMonitoring();
  83003. });
  83004. }
  83005. else {
  83006. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83007. this._onBeforeShaderCompilationObserver = null;
  83008. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83009. this._onAfterShaderCompilationObserver = null;
  83010. }
  83011. },
  83012. enumerable: true,
  83013. configurable: true
  83014. });
  83015. EngineInstrumentation.prototype.dispose = function () {
  83016. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  83017. this._onBeginFrameObserver = null;
  83018. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  83019. this._onEndFrameObserver = null;
  83020. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  83021. this._onBeforeShaderCompilationObserver = null;
  83022. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  83023. this._onAfterShaderCompilationObserver = null;
  83024. this.engine = null;
  83025. };
  83026. return EngineInstrumentation;
  83027. }());
  83028. BABYLON.EngineInstrumentation = EngineInstrumentation;
  83029. })(BABYLON || (BABYLON = {}));
  83030. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  83031. var BABYLON;
  83032. (function (BABYLON) {
  83033. /**
  83034. * This class can be used to get instrumentation data from a Babylon engine
  83035. */
  83036. var SceneInstrumentation = /** @class */ (function () {
  83037. function SceneInstrumentation(scene) {
  83038. var _this = this;
  83039. this.scene = scene;
  83040. this._captureActiveMeshesEvaluationTime = false;
  83041. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  83042. this._captureRenderTargetsRenderTime = false;
  83043. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  83044. this._captureFrameTime = false;
  83045. this._frameTime = new BABYLON.PerfCounter();
  83046. this._captureRenderTime = false;
  83047. this._renderTime = new BABYLON.PerfCounter();
  83048. this._captureInterFrameTime = false;
  83049. this._interFrameTime = new BABYLON.PerfCounter();
  83050. this._captureParticlesRenderTime = false;
  83051. this._particlesRenderTime = new BABYLON.PerfCounter();
  83052. this._captureSpritesRenderTime = false;
  83053. this._spritesRenderTime = new BABYLON.PerfCounter();
  83054. this._capturePhysicsTime = false;
  83055. this._physicsTime = new BABYLON.PerfCounter();
  83056. this._captureAnimationsTime = false;
  83057. this._animationsTime = new BABYLON.PerfCounter();
  83058. // Observers
  83059. this._onBeforeActiveMeshesEvaluationObserver = null;
  83060. this._onAfterActiveMeshesEvaluationObserver = null;
  83061. this._onBeforeRenderTargetsRenderObserver = null;
  83062. this._onAfterRenderTargetsRenderObserver = null;
  83063. this._onAfterRenderObserver = null;
  83064. this._onBeforeDrawPhaseObserver = null;
  83065. this._onAfterDrawPhaseObserver = null;
  83066. this._onBeforeAnimationsObserver = null;
  83067. this._onBeforeParticlesRenderingObserver = null;
  83068. this._onAfterParticlesRenderingObserver = null;
  83069. this._onBeforeSpritesRenderingObserver = null;
  83070. this._onAfterSpritesRenderingObserver = null;
  83071. this._onBeforePhysicsObserver = null;
  83072. this._onAfterPhysicsObserver = null;
  83073. this._onAfterAnimationsObserver = null;
  83074. // Before render
  83075. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  83076. if (_this._captureActiveMeshesEvaluationTime) {
  83077. _this._activeMeshesEvaluationTime.fetchNewFrame();
  83078. }
  83079. if (_this._captureRenderTargetsRenderTime) {
  83080. _this._renderTargetsRenderTime.fetchNewFrame();
  83081. }
  83082. if (_this._captureFrameTime) {
  83083. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  83084. _this._frameTime.beginMonitoring();
  83085. }
  83086. if (_this._captureInterFrameTime) {
  83087. _this._interFrameTime.endMonitoring();
  83088. }
  83089. if (_this._captureParticlesRenderTime) {
  83090. _this._particlesRenderTime.fetchNewFrame();
  83091. }
  83092. if (_this._captureSpritesRenderTime) {
  83093. _this._spritesRenderTime.fetchNewFrame();
  83094. }
  83095. if (_this._captureAnimationsTime) {
  83096. _this._animationsTime.beginMonitoring();
  83097. }
  83098. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  83099. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  83100. });
  83101. // After render
  83102. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  83103. if (_this._captureFrameTime) {
  83104. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  83105. _this._frameTime.endMonitoring();
  83106. }
  83107. if (_this._captureRenderTime) {
  83108. _this._renderTime.endMonitoring(false);
  83109. }
  83110. if (_this._captureInterFrameTime) {
  83111. _this._interFrameTime.beginMonitoring();
  83112. }
  83113. });
  83114. }
  83115. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  83116. // Properties
  83117. /**
  83118. * Gets the perf counter used for active meshes evaluation time
  83119. */
  83120. get: function () {
  83121. return this._activeMeshesEvaluationTime;
  83122. },
  83123. enumerable: true,
  83124. configurable: true
  83125. });
  83126. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  83127. /**
  83128. * Gets the active meshes evaluation time capture status
  83129. */
  83130. get: function () {
  83131. return this._captureActiveMeshesEvaluationTime;
  83132. },
  83133. /**
  83134. * Enable or disable the active meshes evaluation time capture
  83135. */
  83136. set: function (value) {
  83137. var _this = this;
  83138. if (value === this._captureActiveMeshesEvaluationTime) {
  83139. return;
  83140. }
  83141. this._captureActiveMeshesEvaluationTime = value;
  83142. if (value) {
  83143. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  83144. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  83145. _this._activeMeshesEvaluationTime.beginMonitoring();
  83146. });
  83147. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  83148. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  83149. _this._activeMeshesEvaluationTime.endMonitoring();
  83150. });
  83151. }
  83152. else {
  83153. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83154. this._onBeforeActiveMeshesEvaluationObserver = null;
  83155. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83156. this._onAfterActiveMeshesEvaluationObserver = null;
  83157. }
  83158. },
  83159. enumerable: true,
  83160. configurable: true
  83161. });
  83162. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  83163. /**
  83164. * Gets the perf counter used for render targets render time
  83165. */
  83166. get: function () {
  83167. return this._renderTargetsRenderTime;
  83168. },
  83169. enumerable: true,
  83170. configurable: true
  83171. });
  83172. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  83173. /**
  83174. * Gets the render targets render time capture status
  83175. */
  83176. get: function () {
  83177. return this._captureRenderTargetsRenderTime;
  83178. },
  83179. /**
  83180. * Enable or disable the render targets render time capture
  83181. */
  83182. set: function (value) {
  83183. var _this = this;
  83184. if (value === this._captureRenderTargetsRenderTime) {
  83185. return;
  83186. }
  83187. this._captureRenderTargetsRenderTime = value;
  83188. if (value) {
  83189. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  83190. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  83191. _this._renderTargetsRenderTime.beginMonitoring();
  83192. });
  83193. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  83194. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  83195. _this._renderTargetsRenderTime.endMonitoring(false);
  83196. });
  83197. }
  83198. else {
  83199. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83200. this._onBeforeRenderTargetsRenderObserver = null;
  83201. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83202. this._onAfterRenderTargetsRenderObserver = null;
  83203. }
  83204. },
  83205. enumerable: true,
  83206. configurable: true
  83207. });
  83208. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  83209. /**
  83210. * Gets the perf counter used for particles render time
  83211. */
  83212. get: function () {
  83213. return this._particlesRenderTime;
  83214. },
  83215. enumerable: true,
  83216. configurable: true
  83217. });
  83218. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  83219. /**
  83220. * Gets the particles render time capture status
  83221. */
  83222. get: function () {
  83223. return this._captureParticlesRenderTime;
  83224. },
  83225. /**
  83226. * Enable or disable the particles render time capture
  83227. */
  83228. set: function (value) {
  83229. var _this = this;
  83230. if (value === this._captureParticlesRenderTime) {
  83231. return;
  83232. }
  83233. this._captureParticlesRenderTime = value;
  83234. if (value) {
  83235. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  83236. BABYLON.Tools.StartPerformanceCounter("Particles");
  83237. _this._particlesRenderTime.beginMonitoring();
  83238. });
  83239. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  83240. BABYLON.Tools.EndPerformanceCounter("Particles");
  83241. _this._particlesRenderTime.endMonitoring(false);
  83242. });
  83243. }
  83244. else {
  83245. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83246. this._onBeforeParticlesRenderingObserver = null;
  83247. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83248. this._onAfterParticlesRenderingObserver = null;
  83249. }
  83250. },
  83251. enumerable: true,
  83252. configurable: true
  83253. });
  83254. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  83255. /**
  83256. * Gets the perf counter used for sprites render time
  83257. */
  83258. get: function () {
  83259. return this._spritesRenderTime;
  83260. },
  83261. enumerable: true,
  83262. configurable: true
  83263. });
  83264. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  83265. /**
  83266. * Gets the sprites render time capture status
  83267. */
  83268. get: function () {
  83269. return this._captureSpritesRenderTime;
  83270. },
  83271. /**
  83272. * Enable or disable the sprites render time capture
  83273. */
  83274. set: function (value) {
  83275. var _this = this;
  83276. if (value === this._captureSpritesRenderTime) {
  83277. return;
  83278. }
  83279. this._captureSpritesRenderTime = value;
  83280. if (value) {
  83281. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  83282. BABYLON.Tools.StartPerformanceCounter("Sprites");
  83283. _this._spritesRenderTime.beginMonitoring();
  83284. });
  83285. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  83286. BABYLON.Tools.EndPerformanceCounter("Sprites");
  83287. _this._spritesRenderTime.endMonitoring(false);
  83288. });
  83289. }
  83290. else {
  83291. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83292. this._onBeforeSpritesRenderingObserver = null;
  83293. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83294. this._onAfterSpritesRenderingObserver = null;
  83295. }
  83296. },
  83297. enumerable: true,
  83298. configurable: true
  83299. });
  83300. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  83301. /**
  83302. * Gets the perf counter used for physics time
  83303. */
  83304. get: function () {
  83305. return this._physicsTime;
  83306. },
  83307. enumerable: true,
  83308. configurable: true
  83309. });
  83310. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  83311. /**
  83312. * Gets the physics time capture status
  83313. */
  83314. get: function () {
  83315. return this._capturePhysicsTime;
  83316. },
  83317. /**
  83318. * Enable or disable the physics time capture
  83319. */
  83320. set: function (value) {
  83321. var _this = this;
  83322. if (value === this._capturePhysicsTime) {
  83323. return;
  83324. }
  83325. this._capturePhysicsTime = value;
  83326. if (value) {
  83327. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  83328. BABYLON.Tools.StartPerformanceCounter("Physics");
  83329. _this._physicsTime.beginMonitoring();
  83330. });
  83331. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  83332. BABYLON.Tools.EndPerformanceCounter("Physics");
  83333. _this._physicsTime.endMonitoring();
  83334. });
  83335. }
  83336. else {
  83337. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83338. this._onBeforePhysicsObserver = null;
  83339. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83340. this._onAfterPhysicsObserver = null;
  83341. }
  83342. },
  83343. enumerable: true,
  83344. configurable: true
  83345. });
  83346. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  83347. /**
  83348. * Gets the perf counter used for animations time
  83349. */
  83350. get: function () {
  83351. return this._animationsTime;
  83352. },
  83353. enumerable: true,
  83354. configurable: true
  83355. });
  83356. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  83357. /**
  83358. * Gets the animations time capture status
  83359. */
  83360. get: function () {
  83361. return this._captureAnimationsTime;
  83362. },
  83363. /**
  83364. * Enable or disable the animations time capture
  83365. */
  83366. set: function (value) {
  83367. var _this = this;
  83368. if (value === this._captureAnimationsTime) {
  83369. return;
  83370. }
  83371. this._captureAnimationsTime = value;
  83372. if (value) {
  83373. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  83374. _this._animationsTime.endMonitoring();
  83375. });
  83376. }
  83377. else {
  83378. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83379. this._onAfterAnimationsObserver = null;
  83380. }
  83381. },
  83382. enumerable: true,
  83383. configurable: true
  83384. });
  83385. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  83386. /**
  83387. * Gets the perf counter used for frame time capture
  83388. */
  83389. get: function () {
  83390. return this._frameTime;
  83391. },
  83392. enumerable: true,
  83393. configurable: true
  83394. });
  83395. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  83396. /**
  83397. * Gets the frame time capture status
  83398. */
  83399. get: function () {
  83400. return this._captureFrameTime;
  83401. },
  83402. /**
  83403. * Enable or disable the frame time capture
  83404. */
  83405. set: function (value) {
  83406. this._captureFrameTime = value;
  83407. },
  83408. enumerable: true,
  83409. configurable: true
  83410. });
  83411. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  83412. /**
  83413. * Gets the perf counter used for inter-frames time capture
  83414. */
  83415. get: function () {
  83416. return this._interFrameTime;
  83417. },
  83418. enumerable: true,
  83419. configurable: true
  83420. });
  83421. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  83422. /**
  83423. * Gets the inter-frames time capture status
  83424. */
  83425. get: function () {
  83426. return this._captureInterFrameTime;
  83427. },
  83428. /**
  83429. * Enable or disable the inter-frames time capture
  83430. */
  83431. set: function (value) {
  83432. this._captureInterFrameTime = value;
  83433. },
  83434. enumerable: true,
  83435. configurable: true
  83436. });
  83437. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  83438. /**
  83439. * Gets the perf counter used for render time capture
  83440. */
  83441. get: function () {
  83442. return this._renderTime;
  83443. },
  83444. enumerable: true,
  83445. configurable: true
  83446. });
  83447. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  83448. /**
  83449. * Gets the render time capture status
  83450. */
  83451. get: function () {
  83452. return this._captureRenderTime;
  83453. },
  83454. /**
  83455. * Enable or disable the render time capture
  83456. */
  83457. set: function (value) {
  83458. var _this = this;
  83459. if (value === this._captureRenderTime) {
  83460. return;
  83461. }
  83462. this._captureRenderTime = value;
  83463. if (value) {
  83464. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  83465. _this._renderTime.beginMonitoring();
  83466. BABYLON.Tools.StartPerformanceCounter("Main render");
  83467. });
  83468. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  83469. _this._renderTime.endMonitoring(false);
  83470. BABYLON.Tools.EndPerformanceCounter("Main render");
  83471. });
  83472. }
  83473. else {
  83474. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83475. this._onBeforeDrawPhaseObserver = null;
  83476. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83477. this._onAfterDrawPhaseObserver = null;
  83478. }
  83479. },
  83480. enumerable: true,
  83481. configurable: true
  83482. });
  83483. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  83484. /**
  83485. * Gets the perf counter used for draw calls
  83486. */
  83487. get: function () {
  83488. return this.scene.getEngine()._drawCalls;
  83489. },
  83490. enumerable: true,
  83491. configurable: true
  83492. });
  83493. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  83494. /**
  83495. * Gets the perf counter used for texture collisions
  83496. */
  83497. get: function () {
  83498. return this.scene.getEngine()._textureCollisions;
  83499. },
  83500. enumerable: true,
  83501. configurable: true
  83502. });
  83503. SceneInstrumentation.prototype.dispose = function () {
  83504. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  83505. this._onAfterRenderObserver = null;
  83506. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83507. this._onBeforeActiveMeshesEvaluationObserver = null;
  83508. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83509. this._onAfterActiveMeshesEvaluationObserver = null;
  83510. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83511. this._onBeforeRenderTargetsRenderObserver = null;
  83512. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83513. this._onAfterRenderTargetsRenderObserver = null;
  83514. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  83515. this._onBeforeAnimationsObserver = null;
  83516. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83517. this._onBeforeParticlesRenderingObserver = null;
  83518. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83519. this._onAfterParticlesRenderingObserver = null;
  83520. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83521. this._onBeforeSpritesRenderingObserver = null;
  83522. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83523. this._onAfterSpritesRenderingObserver = null;
  83524. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83525. this._onBeforeDrawPhaseObserver = null;
  83526. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83527. this._onAfterDrawPhaseObserver = null;
  83528. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83529. this._onBeforePhysicsObserver = null;
  83530. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83531. this._onAfterPhysicsObserver = null;
  83532. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83533. this._onAfterAnimationsObserver = null;
  83534. this.scene = null;
  83535. };
  83536. return SceneInstrumentation;
  83537. }());
  83538. BABYLON.SceneInstrumentation = SceneInstrumentation;
  83539. })(BABYLON || (BABYLON = {}));
  83540. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  83541. var BABYLON;
  83542. (function (BABYLON) {
  83543. var _TimeToken = /** @class */ (function () {
  83544. function _TimeToken() {
  83545. this._timeElapsedQueryEnded = false;
  83546. }
  83547. return _TimeToken;
  83548. }());
  83549. BABYLON._TimeToken = _TimeToken;
  83550. })(BABYLON || (BABYLON = {}));
  83551. //# sourceMappingURL=babylon.timeToken.js.map
  83552. var BABYLON;
  83553. (function (BABYLON) {
  83554. /**
  83555. * Background material defines definition.
  83556. * @ignore Mainly internal Use
  83557. */
  83558. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  83559. __extends(BackgroundMaterialDefines, _super);
  83560. /**
  83561. * Constructor of the defines.
  83562. */
  83563. function BackgroundMaterialDefines() {
  83564. var _this = _super.call(this) || this;
  83565. /**
  83566. * True if the diffuse texture is in use.
  83567. */
  83568. _this.DIFFUSE = false;
  83569. /**
  83570. * The direct UV channel to use.
  83571. */
  83572. _this.DIFFUSEDIRECTUV = 0;
  83573. /**
  83574. * True if the diffuse texture is in gamma space.
  83575. */
  83576. _this.GAMMADIFFUSE = false;
  83577. /**
  83578. * True if the diffuse texture has opacity in the alpha channel.
  83579. */
  83580. _this.DIFFUSEHASALPHA = false;
  83581. /**
  83582. * True if you want the material to fade to transparent at grazing angle.
  83583. */
  83584. _this.OPACITYFRESNEL = false;
  83585. /**
  83586. * True if an extra blur needs to be added in the reflection.
  83587. */
  83588. _this.REFLECTIONBLUR = false;
  83589. /**
  83590. * True if you want the material to fade to reflection at grazing angle.
  83591. */
  83592. _this.REFLECTIONFRESNEL = false;
  83593. /**
  83594. * True if you want the material to falloff as far as you move away from the scene center.
  83595. */
  83596. _this.REFLECTIONFALLOFF = false;
  83597. /**
  83598. * False if the current Webgl implementation does not support the texture lod extension.
  83599. */
  83600. _this.TEXTURELODSUPPORT = false;
  83601. /**
  83602. * True to ensure the data are premultiplied.
  83603. */
  83604. _this.PREMULTIPLYALPHA = false;
  83605. /**
  83606. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  83607. */
  83608. _this.USERGBCOLOR = false;
  83609. /**
  83610. * True to add noise in order to reduce the banding effect.
  83611. */
  83612. _this.NOISE = false;
  83613. // Image Processing Configuration.
  83614. _this.IMAGEPROCESSING = false;
  83615. _this.VIGNETTE = false;
  83616. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83617. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83618. _this.TONEMAPPING = false;
  83619. _this.CONTRAST = false;
  83620. _this.COLORCURVES = false;
  83621. _this.COLORGRADING = false;
  83622. _this.COLORGRADING3D = false;
  83623. _this.SAMPLER3DGREENDEPTH = false;
  83624. _this.SAMPLER3DBGRMAP = false;
  83625. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83626. _this.EXPOSURE = false;
  83627. // Reflection.
  83628. _this.REFLECTION = false;
  83629. _this.REFLECTIONMAP_3D = false;
  83630. _this.REFLECTIONMAP_SPHERICAL = false;
  83631. _this.REFLECTIONMAP_PLANAR = false;
  83632. _this.REFLECTIONMAP_CUBIC = false;
  83633. _this.REFLECTIONMAP_PROJECTION = false;
  83634. _this.REFLECTIONMAP_SKYBOX = false;
  83635. _this.REFLECTIONMAP_EXPLICIT = false;
  83636. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83637. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83638. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83639. _this.INVERTCUBICMAP = false;
  83640. _this.REFLECTIONMAP_OPPOSITEZ = false;
  83641. _this.LODINREFLECTIONALPHA = false;
  83642. _this.GAMMAREFLECTION = false;
  83643. // Default BJS.
  83644. _this.MAINUV1 = false;
  83645. _this.MAINUV2 = false;
  83646. _this.UV1 = false;
  83647. _this.UV2 = false;
  83648. _this.CLIPPLANE = false;
  83649. _this.POINTSIZE = false;
  83650. _this.FOG = false;
  83651. _this.NORMAL = false;
  83652. _this.NUM_BONE_INFLUENCERS = 0;
  83653. _this.BonesPerMesh = 0;
  83654. _this.INSTANCES = false;
  83655. _this.SHADOWFLOAT = false;
  83656. _this.rebuild();
  83657. return _this;
  83658. }
  83659. return BackgroundMaterialDefines;
  83660. }(BABYLON.MaterialDefines));
  83661. /**
  83662. * Background material used to create an efficient environement around your scene.
  83663. */
  83664. var BackgroundMaterial = /** @class */ (function (_super) {
  83665. __extends(BackgroundMaterial, _super);
  83666. /**
  83667. * Instantiates a Background Material in the given scene
  83668. * @param name The friendly name of the material
  83669. * @param scene The scene to add the material to
  83670. */
  83671. function BackgroundMaterial(name, scene) {
  83672. var _this = _super.call(this, name, scene) || this;
  83673. /**
  83674. * Key light Color (multiply against the R channel of the environement texture)
  83675. */
  83676. _this.primaryColor = BABYLON.Color3.White();
  83677. /**
  83678. * Key light Level (allowing HDR output of the background)
  83679. */
  83680. _this.primaryLevel = 1;
  83681. /**
  83682. * Secondary light Color (multiply against the G channel of the environement texture)
  83683. */
  83684. _this.secondaryColor = BABYLON.Color3.Gray();
  83685. /**
  83686. * Secondary light Level (allowing HDR output of the background)
  83687. */
  83688. _this.secondaryLevel = 1;
  83689. /**
  83690. * Tertiary light Color (multiply against the B channel of the environement texture)
  83691. */
  83692. _this.tertiaryColor = BABYLON.Color3.Black();
  83693. /**
  83694. * Tertiary light Level (allowing HDR output of the background)
  83695. */
  83696. _this.tertiaryLevel = 1;
  83697. /**
  83698. * Reflection Texture used in the material.
  83699. * Should be author in a specific way for the best result (refer to the documentation).
  83700. */
  83701. _this.reflectionTexture = null;
  83702. /**
  83703. * Reflection Texture level of blur.
  83704. *
  83705. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  83706. * texture twice.
  83707. */
  83708. _this.reflectionBlur = 0;
  83709. /**
  83710. * Diffuse Texture used in the material.
  83711. * Should be author in a specific way for the best result (refer to the documentation).
  83712. */
  83713. _this.diffuseTexture = null;
  83714. _this._shadowLights = null;
  83715. /**
  83716. * Specify the list of lights casting shadow on the material.
  83717. * All scene shadow lights will be included if null.
  83718. */
  83719. _this.shadowLights = null;
  83720. /**
  83721. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  83722. * soft lighting on the background.
  83723. */
  83724. _this.shadowBlurScale = 1;
  83725. /**
  83726. * Helps adjusting the shadow to a softer level if required.
  83727. * 0 means black shadows and 1 means no shadows.
  83728. */
  83729. _this.shadowLevel = 0;
  83730. /**
  83731. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  83732. * It is usually zero but might be interesting to modify according to your setup.
  83733. */
  83734. _this.sceneCenter = BABYLON.Vector3.Zero();
  83735. /**
  83736. * This helps specifying that the material is falling off to the sky box at grazing angle.
  83737. * This helps ensuring a nice transition when the camera goes under the ground.
  83738. */
  83739. _this.opacityFresnel = true;
  83740. /**
  83741. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  83742. * This helps adding a mirror texture on the ground.
  83743. */
  83744. _this.reflectionFresnel = false;
  83745. /**
  83746. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  83747. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  83748. */
  83749. _this.reflectionFalloffDistance = 0.0;
  83750. /**
  83751. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  83752. */
  83753. _this.reflectionAmount = 1.0;
  83754. /**
  83755. * This specifies the weight of the reflection at grazing angle.
  83756. */
  83757. _this.reflectionReflectance0 = 0.05;
  83758. /**
  83759. * This specifies the weight of the reflection at a perpendicular point of view.
  83760. */
  83761. _this.reflectionReflectance90 = 0.5;
  83762. /**
  83763. * Helps to directly use the maps channels instead of their level.
  83764. */
  83765. _this.useRGBColor = true;
  83766. /**
  83767. * This helps reducing the banding effect that could occur on the background.
  83768. */
  83769. _this.enableNoise = false;
  83770. _this._maxSimultaneousLights = 4;
  83771. /**
  83772. * Number of Simultaneous lights allowed on the material.
  83773. */
  83774. _this.maxSimultaneousLights = 4;
  83775. /**
  83776. * Keep track of the image processing observer to allow dispose and replace.
  83777. */
  83778. _this._imageProcessingObserver = null;
  83779. // Temp values kept as cache in the material.
  83780. _this._renderTargets = new BABYLON.SmartArray(16);
  83781. _this._reflectionControls = BABYLON.Vector4.Zero();
  83782. // Setup the default processing configuration to the scene.
  83783. _this._attachImageProcessingConfiguration(null);
  83784. _this.getRenderTargetTextures = function () {
  83785. _this._renderTargets.reset();
  83786. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  83787. _this._renderTargets.push(_this._diffuseTexture);
  83788. }
  83789. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  83790. _this._renderTargets.push(_this._reflectionTexture);
  83791. }
  83792. return _this._renderTargets;
  83793. };
  83794. return _this;
  83795. }
  83796. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  83797. /**
  83798. * Sets the reflection reflectance fresnel values according to the default standard
  83799. * empirically know to work well :-)
  83800. */
  83801. set: function (value) {
  83802. var reflectionWeight = value;
  83803. if (reflectionWeight < 0.5) {
  83804. reflectionWeight = reflectionWeight * 2.0;
  83805. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  83806. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  83807. }
  83808. else {
  83809. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  83810. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  83811. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  83812. }
  83813. },
  83814. enumerable: true,
  83815. configurable: true
  83816. });
  83817. /**
  83818. * Attaches a new image processing configuration to the PBR Material.
  83819. * @param configuration (if null the scene configuration will be use)
  83820. */
  83821. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  83822. var _this = this;
  83823. if (configuration === this._imageProcessingConfiguration) {
  83824. return;
  83825. }
  83826. // Detaches observer.
  83827. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83828. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83829. }
  83830. // Pick the scene configuration if needed.
  83831. if (!configuration) {
  83832. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  83833. }
  83834. else {
  83835. this._imageProcessingConfiguration = configuration;
  83836. }
  83837. // Attaches observer.
  83838. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83839. _this._markAllSubMeshesAsImageProcessingDirty();
  83840. });
  83841. };
  83842. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  83843. /**
  83844. * Gets the image processing configuration used either in this material.
  83845. */
  83846. get: function () {
  83847. return this._imageProcessingConfiguration;
  83848. },
  83849. /**
  83850. * Sets the Default image processing configuration used either in the this material.
  83851. *
  83852. * If sets to null, the scene one is in use.
  83853. */
  83854. set: function (value) {
  83855. this._attachImageProcessingConfiguration(value);
  83856. // Ensure the effect will be rebuilt.
  83857. this._markAllSubMeshesAsTexturesDirty();
  83858. },
  83859. enumerable: true,
  83860. configurable: true
  83861. });
  83862. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  83863. /**
  83864. * Gets wether the color curves effect is enabled.
  83865. */
  83866. get: function () {
  83867. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83868. },
  83869. /**
  83870. * Sets wether the color curves effect is enabled.
  83871. */
  83872. set: function (value) {
  83873. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83874. },
  83875. enumerable: true,
  83876. configurable: true
  83877. });
  83878. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  83879. /**
  83880. * Gets wether the color grading effect is enabled.
  83881. */
  83882. get: function () {
  83883. return this.imageProcessingConfiguration.colorGradingEnabled;
  83884. },
  83885. /**
  83886. * Gets wether the color grading effect is enabled.
  83887. */
  83888. set: function (value) {
  83889. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83890. },
  83891. enumerable: true,
  83892. configurable: true
  83893. });
  83894. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  83895. /**
  83896. * Gets wether tonemapping is enabled or not.
  83897. */
  83898. get: function () {
  83899. return this._imageProcessingConfiguration.toneMappingEnabled;
  83900. },
  83901. /**
  83902. * Sets wether tonemapping is enabled or not
  83903. */
  83904. set: function (value) {
  83905. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83906. },
  83907. enumerable: true,
  83908. configurable: true
  83909. });
  83910. ;
  83911. ;
  83912. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  83913. /**
  83914. * The camera exposure used on this material.
  83915. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83916. * This corresponds to a photographic exposure.
  83917. */
  83918. get: function () {
  83919. return this._imageProcessingConfiguration.exposure;
  83920. },
  83921. /**
  83922. * The camera exposure used on this material.
  83923. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83924. * This corresponds to a photographic exposure.
  83925. */
  83926. set: function (value) {
  83927. this._imageProcessingConfiguration.exposure = value;
  83928. },
  83929. enumerable: true,
  83930. configurable: true
  83931. });
  83932. ;
  83933. ;
  83934. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  83935. /**
  83936. * Gets The camera contrast used on this material.
  83937. */
  83938. get: function () {
  83939. return this._imageProcessingConfiguration.contrast;
  83940. },
  83941. /**
  83942. * Sets The camera contrast used on this material.
  83943. */
  83944. set: function (value) {
  83945. this._imageProcessingConfiguration.contrast = value;
  83946. },
  83947. enumerable: true,
  83948. configurable: true
  83949. });
  83950. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  83951. /**
  83952. * Gets the Color Grading 2D Lookup Texture.
  83953. */
  83954. get: function () {
  83955. return this._imageProcessingConfiguration.colorGradingTexture;
  83956. },
  83957. /**
  83958. * Sets the Color Grading 2D Lookup Texture.
  83959. */
  83960. set: function (value) {
  83961. this.imageProcessingConfiguration.colorGradingTexture = value;
  83962. },
  83963. enumerable: true,
  83964. configurable: true
  83965. });
  83966. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  83967. /**
  83968. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83969. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83970. * 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;
  83971. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83972. */
  83973. get: function () {
  83974. return this.imageProcessingConfiguration.colorCurves;
  83975. },
  83976. /**
  83977. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83978. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83979. * 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;
  83980. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83981. */
  83982. set: function (value) {
  83983. this.imageProcessingConfiguration.colorCurves = value;
  83984. },
  83985. enumerable: true,
  83986. configurable: true
  83987. });
  83988. /**
  83989. * The entire material has been created in order to prevent overdraw.
  83990. * @returns false
  83991. */
  83992. BackgroundMaterial.prototype.needAlphaTesting = function () {
  83993. return true;
  83994. };
  83995. /**
  83996. * The entire material has been created in order to prevent overdraw.
  83997. * @returns true if blending is enable
  83998. */
  83999. BackgroundMaterial.prototype.needAlphaBlending = function () {
  84000. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  84001. };
  84002. /**
  84003. * Checks wether the material is ready to be rendered for a given mesh.
  84004. * @param mesh The mesh to render
  84005. * @param subMesh The submesh to check against
  84006. * @param useInstances Specify wether or not the material is used with instances
  84007. * @returns true if all the dependencies are ready (Textures, Effects...)
  84008. */
  84009. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  84010. var _this = this;
  84011. if (useInstances === void 0) { useInstances = false; }
  84012. if (subMesh.effect && this.isFrozen) {
  84013. if (this._wasPreviouslyReady) {
  84014. return true;
  84015. }
  84016. }
  84017. if (!subMesh._materialDefines) {
  84018. subMesh._materialDefines = new BackgroundMaterialDefines();
  84019. }
  84020. var scene = this.getScene();
  84021. var defines = subMesh._materialDefines;
  84022. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  84023. if (defines._renderId === scene.getRenderId()) {
  84024. return true;
  84025. }
  84026. }
  84027. var engine = scene.getEngine();
  84028. // Lights
  84029. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  84030. defines._needNormals = true;
  84031. // Textures
  84032. if (defines._areTexturesDirty) {
  84033. defines._needUVs = false;
  84034. if (scene.texturesEnabled) {
  84035. if (scene.getEngine().getCaps().textureLOD) {
  84036. defines.TEXTURELODSUPPORT = true;
  84037. }
  84038. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84039. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  84040. return false;
  84041. }
  84042. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  84043. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  84044. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  84045. defines.OPACITYFRESNEL = this._opacityFresnel;
  84046. }
  84047. else {
  84048. defines.DIFFUSE = false;
  84049. defines.DIFFUSEHASALPHA = false;
  84050. defines.GAMMADIFFUSE = false;
  84051. defines.OPACITYFRESNEL = false;
  84052. }
  84053. var reflectionTexture = this._reflectionTexture;
  84054. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84055. if (!reflectionTexture.isReadyOrNotBlocking()) {
  84056. return false;
  84057. }
  84058. defines.REFLECTION = true;
  84059. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  84060. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  84061. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  84062. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  84063. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  84064. defines.INVERTCUBICMAP = true;
  84065. }
  84066. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  84067. switch (reflectionTexture.coordinatesMode) {
  84068. case BABYLON.Texture.CUBIC_MODE:
  84069. case BABYLON.Texture.INVCUBIC_MODE:
  84070. defines.REFLECTIONMAP_CUBIC = true;
  84071. break;
  84072. case BABYLON.Texture.EXPLICIT_MODE:
  84073. defines.REFLECTIONMAP_EXPLICIT = true;
  84074. break;
  84075. case BABYLON.Texture.PLANAR_MODE:
  84076. defines.REFLECTIONMAP_PLANAR = true;
  84077. break;
  84078. case BABYLON.Texture.PROJECTION_MODE:
  84079. defines.REFLECTIONMAP_PROJECTION = true;
  84080. break;
  84081. case BABYLON.Texture.SKYBOX_MODE:
  84082. defines.REFLECTIONMAP_SKYBOX = true;
  84083. break;
  84084. case BABYLON.Texture.SPHERICAL_MODE:
  84085. defines.REFLECTIONMAP_SPHERICAL = true;
  84086. break;
  84087. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  84088. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  84089. break;
  84090. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  84091. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  84092. break;
  84093. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  84094. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  84095. break;
  84096. }
  84097. if (this.reflectionFresnel) {
  84098. defines.REFLECTIONFRESNEL = true;
  84099. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  84100. this._reflectionControls.x = this.reflectionAmount;
  84101. this._reflectionControls.y = this.reflectionReflectance0;
  84102. this._reflectionControls.z = this.reflectionReflectance90;
  84103. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  84104. }
  84105. else {
  84106. defines.REFLECTIONFRESNEL = false;
  84107. defines.REFLECTIONFALLOFF = false;
  84108. }
  84109. }
  84110. else {
  84111. defines.REFLECTION = false;
  84112. defines.REFLECTIONFALLOFF = false;
  84113. defines.REFLECTIONBLUR = false;
  84114. defines.REFLECTIONMAP_3D = false;
  84115. defines.REFLECTIONMAP_SPHERICAL = false;
  84116. defines.REFLECTIONMAP_PLANAR = false;
  84117. defines.REFLECTIONMAP_CUBIC = false;
  84118. defines.REFLECTIONMAP_PROJECTION = false;
  84119. defines.REFLECTIONMAP_SKYBOX = false;
  84120. defines.REFLECTIONMAP_EXPLICIT = false;
  84121. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  84122. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  84123. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  84124. defines.INVERTCUBICMAP = false;
  84125. defines.REFLECTIONMAP_OPPOSITEZ = false;
  84126. defines.LODINREFLECTIONALPHA = false;
  84127. defines.GAMMAREFLECTION = false;
  84128. }
  84129. }
  84130. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  84131. defines.USERGBCOLOR = this._useRGBColor;
  84132. defines.NOISE = this._enableNoise;
  84133. }
  84134. if (defines._areImageProcessingDirty) {
  84135. if (!this._imageProcessingConfiguration.isReady()) {
  84136. return false;
  84137. }
  84138. this._imageProcessingConfiguration.prepareDefines(defines);
  84139. }
  84140. // Misc.
  84141. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  84142. // Values that need to be evaluated on every frame
  84143. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  84144. // Attribs
  84145. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  84146. if (mesh) {
  84147. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84148. mesh.createNormals(true);
  84149. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  84150. }
  84151. }
  84152. }
  84153. // Get correct effect
  84154. if (defines.isDirty) {
  84155. defines.markAsProcessed();
  84156. scene.resetCachedMaterial();
  84157. // Fallbacks
  84158. var fallbacks = new BABYLON.EffectFallbacks();
  84159. if (defines.FOG) {
  84160. fallbacks.addFallback(0, "FOG");
  84161. }
  84162. if (defines.POINTSIZE) {
  84163. fallbacks.addFallback(1, "POINTSIZE");
  84164. }
  84165. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  84166. if (defines.NUM_BONE_INFLUENCERS > 0) {
  84167. fallbacks.addCPUSkinningFallback(0, mesh);
  84168. }
  84169. //Attributes
  84170. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84171. if (defines.NORMAL) {
  84172. attribs.push(BABYLON.VertexBuffer.NormalKind);
  84173. }
  84174. if (defines.UV1) {
  84175. attribs.push(BABYLON.VertexBuffer.UVKind);
  84176. }
  84177. if (defines.UV2) {
  84178. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84179. }
  84180. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  84181. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  84182. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  84183. "vFogInfos", "vFogColor", "pointSize",
  84184. "vClipPlane", "mBones",
  84185. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  84186. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  84187. "shadowLevel", "alpha",
  84188. "vBackgroundCenter", "vReflectionControl",
  84189. "vDiffuseInfos", "diffuseMatrix",
  84190. ];
  84191. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  84192. var uniformBuffers = ["Material", "Scene"];
  84193. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  84194. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  84195. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  84196. uniformsNames: uniforms,
  84197. uniformBuffersNames: uniformBuffers,
  84198. samplers: samplers,
  84199. defines: defines,
  84200. maxSimultaneousLights: this._maxSimultaneousLights
  84201. });
  84202. var onCompiled = function (effect) {
  84203. if (_this.onCompiled) {
  84204. _this.onCompiled(effect);
  84205. }
  84206. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  84207. };
  84208. var join = defines.toString();
  84209. subMesh.setEffect(scene.getEngine().createEffect("background", {
  84210. attributes: attribs,
  84211. uniformsNames: uniforms,
  84212. uniformBuffersNames: uniformBuffers,
  84213. samplers: samplers,
  84214. defines: join,
  84215. fallbacks: fallbacks,
  84216. onCompiled: onCompiled,
  84217. onError: this.onError,
  84218. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  84219. }, engine), defines);
  84220. this.buildUniformLayout();
  84221. }
  84222. if (!subMesh.effect || !subMesh.effect.isReady()) {
  84223. return false;
  84224. }
  84225. defines._renderId = scene.getRenderId();
  84226. this._wasPreviouslyReady = true;
  84227. return true;
  84228. };
  84229. /**
  84230. * Build the uniform buffer used in the material.
  84231. */
  84232. BackgroundMaterial.prototype.buildUniformLayout = function () {
  84233. // Order is important !
  84234. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  84235. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  84236. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  84237. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  84238. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  84239. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  84240. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  84241. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  84242. this._uniformBuffer.addUniform("pointSize", 1);
  84243. this._uniformBuffer.addUniform("shadowLevel", 1);
  84244. this._uniformBuffer.addUniform("alpha", 1);
  84245. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  84246. this._uniformBuffer.addUniform("vReflectionControl", 4);
  84247. this._uniformBuffer.create();
  84248. };
  84249. /**
  84250. * Unbind the material.
  84251. */
  84252. BackgroundMaterial.prototype.unbind = function () {
  84253. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  84254. this._uniformBuffer.setTexture("diffuseSampler", null);
  84255. }
  84256. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  84257. this._uniformBuffer.setTexture("reflectionSampler", null);
  84258. }
  84259. _super.prototype.unbind.call(this);
  84260. };
  84261. /**
  84262. * Bind only the world matrix to the material.
  84263. * @param world The world matrix to bind.
  84264. */
  84265. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  84266. this._activeEffect.setMatrix("world", world);
  84267. };
  84268. /**
  84269. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  84270. * @param world The world matrix to bind.
  84271. * @param subMesh The submesh to bind for.
  84272. */
  84273. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  84274. var scene = this.getScene();
  84275. var defines = subMesh._materialDefines;
  84276. if (!defines) {
  84277. return;
  84278. }
  84279. var effect = subMesh.effect;
  84280. if (!effect) {
  84281. return;
  84282. }
  84283. this._activeEffect = effect;
  84284. // Matrices
  84285. this.bindOnlyWorldMatrix(world);
  84286. // Bones
  84287. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  84288. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  84289. if (mustRebind) {
  84290. this._uniformBuffer.bindToEffect(effect, "Material");
  84291. this.bindViewProjection(effect);
  84292. var reflectionTexture = this._reflectionTexture;
  84293. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  84294. // Texture uniforms
  84295. if (scene.texturesEnabled) {
  84296. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84297. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  84298. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  84299. }
  84300. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84301. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  84302. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  84303. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  84304. }
  84305. }
  84306. if (this.shadowLevel > 0) {
  84307. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  84308. }
  84309. this._uniformBuffer.updateFloat("alpha", this.alpha);
  84310. // Point size
  84311. if (this.pointsCloud) {
  84312. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  84313. }
  84314. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  84315. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  84316. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  84317. }
  84318. // Textures
  84319. if (scene.texturesEnabled) {
  84320. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  84321. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  84322. }
  84323. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  84324. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  84325. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84326. }
  84327. else if (!defines.REFLECTIONBLUR) {
  84328. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  84329. }
  84330. else {
  84331. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  84332. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  84333. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  84334. }
  84335. if (defines.REFLECTIONFRESNEL) {
  84336. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  84337. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  84338. }
  84339. }
  84340. }
  84341. // Clip plane
  84342. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  84343. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  84344. }
  84345. if (mustRebind || !this.isFrozen) {
  84346. if (scene.lightsEnabled) {
  84347. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  84348. }
  84349. // View
  84350. this.bindView(effect);
  84351. // Fog
  84352. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  84353. // image processing
  84354. this._imageProcessingConfiguration.bind(this._activeEffect);
  84355. }
  84356. this._uniformBuffer.update();
  84357. this._afterBind(mesh);
  84358. };
  84359. /**
  84360. * Dispose the material.
  84361. * @param forceDisposeEffect Force disposal of the associated effect.
  84362. * @param forceDisposeTextures Force disposal of the associated textures.
  84363. */
  84364. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  84365. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  84366. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  84367. if (forceDisposeTextures) {
  84368. if (this.diffuseTexture) {
  84369. this.diffuseTexture.dispose();
  84370. }
  84371. if (this.reflectionTexture) {
  84372. this.reflectionTexture.dispose();
  84373. }
  84374. }
  84375. this._renderTargets.dispose();
  84376. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84377. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84378. }
  84379. _super.prototype.dispose.call(this, forceDisposeEffect);
  84380. };
  84381. /**
  84382. * Clones the material.
  84383. * @param name The cloned name.
  84384. * @returns The cloned material.
  84385. */
  84386. BackgroundMaterial.prototype.clone = function (name) {
  84387. var _this = this;
  84388. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  84389. };
  84390. /**
  84391. * Serializes the current material to its JSON representation.
  84392. * @returns The JSON representation.
  84393. */
  84394. BackgroundMaterial.prototype.serialize = function () {
  84395. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84396. serializationObject.customType = "BABYLON.BackgroundMaterial";
  84397. return serializationObject;
  84398. };
  84399. /**
  84400. * Gets the class name of the material
  84401. * @returns "BackgroundMaterial"
  84402. */
  84403. BackgroundMaterial.prototype.getClassName = function () {
  84404. return "BackgroundMaterial";
  84405. };
  84406. /**
  84407. * Parse a JSON input to create back a background material.
  84408. * @param source The JSON data to parse
  84409. * @param scene The scene to create the parsed material in
  84410. * @param rootUrl The root url of the assets the material depends upon
  84411. * @returns the instantiated BackgroundMaterial.
  84412. */
  84413. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  84414. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  84415. };
  84416. /**
  84417. * Standard reflectance value at parallel view angle.
  84418. */
  84419. BackgroundMaterial.StandardReflectance0 = 0.05;
  84420. /**
  84421. * Standard reflectance value at grazing angle.
  84422. */
  84423. BackgroundMaterial.StandardReflectance90 = 0.5;
  84424. __decorate([
  84425. BABYLON.serializeAsColor3()
  84426. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  84427. __decorate([
  84428. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84429. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  84430. __decorate([
  84431. BABYLON.serialize()
  84432. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  84433. __decorate([
  84434. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84435. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  84436. __decorate([
  84437. BABYLON.serializeAsColor3()
  84438. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  84439. __decorate([
  84440. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84441. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  84442. __decorate([
  84443. BABYLON.serialize()
  84444. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  84445. __decorate([
  84446. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84447. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  84448. __decorate([
  84449. BABYLON.serializeAsColor3()
  84450. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  84451. __decorate([
  84452. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84453. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  84454. __decorate([
  84455. BABYLON.serialize()
  84456. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  84457. __decorate([
  84458. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84459. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  84460. __decorate([
  84461. BABYLON.serializeAsTexture()
  84462. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  84463. __decorate([
  84464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84465. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  84466. __decorate([
  84467. BABYLON.serialize()
  84468. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  84469. __decorate([
  84470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84471. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  84472. __decorate([
  84473. BABYLON.serializeAsTexture()
  84474. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  84475. __decorate([
  84476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84477. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  84478. __decorate([
  84479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84480. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  84481. __decorate([
  84482. BABYLON.serialize()
  84483. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  84484. __decorate([
  84485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84486. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  84487. __decorate([
  84488. BABYLON.serialize()
  84489. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  84490. __decorate([
  84491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84492. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  84493. __decorate([
  84494. BABYLON.serializeAsVector3()
  84495. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  84496. __decorate([
  84497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84498. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  84499. __decorate([
  84500. BABYLON.serialize()
  84501. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  84502. __decorate([
  84503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84504. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  84505. __decorate([
  84506. BABYLON.serialize()
  84507. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  84508. __decorate([
  84509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84510. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  84511. __decorate([
  84512. BABYLON.serialize()
  84513. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  84514. __decorate([
  84515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84516. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  84517. __decorate([
  84518. BABYLON.serialize()
  84519. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  84520. __decorate([
  84521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84522. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  84523. __decorate([
  84524. BABYLON.serialize()
  84525. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  84526. __decorate([
  84527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84528. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  84529. __decorate([
  84530. BABYLON.serialize()
  84531. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  84532. __decorate([
  84533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84534. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  84535. __decorate([
  84536. BABYLON.serialize()
  84537. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  84538. __decorate([
  84539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84540. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  84541. __decorate([
  84542. BABYLON.serialize()
  84543. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  84544. __decorate([
  84545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84546. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  84547. __decorate([
  84548. BABYLON.serialize()
  84549. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  84550. __decorate([
  84551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84552. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  84553. __decorate([
  84554. BABYLON.serializeAsImageProcessingConfiguration()
  84555. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  84556. return BackgroundMaterial;
  84557. }(BABYLON.PushMaterial));
  84558. BABYLON.BackgroundMaterial = BackgroundMaterial;
  84559. })(BABYLON || (BABYLON = {}));
  84560. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  84561. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84562. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84563. s = arguments[i];
  84564. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84565. t[p] = s[p];
  84566. }
  84567. return t;
  84568. };
  84569. var BABYLON;
  84570. (function (BABYLON) {
  84571. /**
  84572. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  84573. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  84574. * It also helps with the default setup of your imageProcessing configuration.
  84575. */
  84576. var EnvironmentHelper = /** @class */ (function () {
  84577. /**
  84578. * constructor
  84579. * @param options
  84580. * @param scene The scene to add the material to
  84581. */
  84582. function EnvironmentHelper(options, scene) {
  84583. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  84584. this._scene = scene;
  84585. this._setupBackground();
  84586. this._setupImageProcessing();
  84587. }
  84588. /**
  84589. * Creates the default options for the helper.
  84590. */
  84591. EnvironmentHelper._getDefaultOptions = function () {
  84592. return {
  84593. createGround: true,
  84594. groundSize: 15,
  84595. groundTexture: this._groundTextureCDNUrl,
  84596. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84597. groundOpacity: 0.9,
  84598. enableGroundShadow: true,
  84599. groundShadowLevel: 0.5,
  84600. enableGroundMirror: false,
  84601. groundMirrorSizeRatio: 0.3,
  84602. groundMirrorBlurKernel: 64,
  84603. groundMirrorAmount: 1,
  84604. groundMirrorFresnelWeight: 1,
  84605. groundMirrorFallOffDistance: 0,
  84606. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  84607. groundYBias: 0.00001,
  84608. createSkybox: true,
  84609. skyboxSize: 20,
  84610. skyboxTexture: this._skyboxTextureCDNUrl,
  84611. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84612. backgroundYRotation: 0,
  84613. sizeAuto: true,
  84614. rootPosition: BABYLON.Vector3.Zero(),
  84615. setupImageProcessing: true,
  84616. environmentTexture: this._environmentTextureCDNUrl,
  84617. cameraExposure: 0.8,
  84618. cameraContrast: 1.2,
  84619. toneMappingEnabled: true,
  84620. };
  84621. };
  84622. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  84623. /**
  84624. * Gets the root mesh created by the helper.
  84625. */
  84626. get: function () {
  84627. return this._rootMesh;
  84628. },
  84629. enumerable: true,
  84630. configurable: true
  84631. });
  84632. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  84633. /**
  84634. * Gets the skybox created by the helper.
  84635. */
  84636. get: function () {
  84637. return this._skybox;
  84638. },
  84639. enumerable: true,
  84640. configurable: true
  84641. });
  84642. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  84643. /**
  84644. * Gets the skybox texture created by the helper.
  84645. */
  84646. get: function () {
  84647. return this._skyboxTexture;
  84648. },
  84649. enumerable: true,
  84650. configurable: true
  84651. });
  84652. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  84653. /**
  84654. * Gets the skybox material created by the helper.
  84655. */
  84656. get: function () {
  84657. return this._skyboxMaterial;
  84658. },
  84659. enumerable: true,
  84660. configurable: true
  84661. });
  84662. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  84663. /**
  84664. * Gets the ground mesh created by the helper.
  84665. */
  84666. get: function () {
  84667. return this._ground;
  84668. },
  84669. enumerable: true,
  84670. configurable: true
  84671. });
  84672. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  84673. /**
  84674. * Gets the ground texture created by the helper.
  84675. */
  84676. get: function () {
  84677. return this._groundTexture;
  84678. },
  84679. enumerable: true,
  84680. configurable: true
  84681. });
  84682. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  84683. /**
  84684. * Gets the ground mirror created by the helper.
  84685. */
  84686. get: function () {
  84687. return this._groundMirror;
  84688. },
  84689. enumerable: true,
  84690. configurable: true
  84691. });
  84692. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  84693. /**
  84694. * Gets the ground mirror render list to helps pushing the meshes
  84695. * you wish in the ground reflection.
  84696. */
  84697. get: function () {
  84698. if (this._groundMirror) {
  84699. return this._groundMirror.renderList;
  84700. }
  84701. return null;
  84702. },
  84703. enumerable: true,
  84704. configurable: true
  84705. });
  84706. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  84707. /**
  84708. * Gets the ground material created by the helper.
  84709. */
  84710. get: function () {
  84711. return this._groundMaterial;
  84712. },
  84713. enumerable: true,
  84714. configurable: true
  84715. });
  84716. /**
  84717. * Updates the background according to the new options
  84718. * @param options
  84719. */
  84720. EnvironmentHelper.prototype.updateOptions = function (options) {
  84721. var newOptions = __assign({}, this._options, options);
  84722. if (this._ground && !newOptions.createGround) {
  84723. this._ground.dispose();
  84724. this._ground = null;
  84725. }
  84726. if (this._groundMaterial && !newOptions.createGround) {
  84727. this._groundMaterial.dispose();
  84728. this._groundMaterial = null;
  84729. }
  84730. if (this._groundTexture) {
  84731. if (this._options.groundTexture != newOptions.groundTexture) {
  84732. this._groundTexture.dispose();
  84733. this._groundTexture = null;
  84734. }
  84735. }
  84736. if (this._skybox && !newOptions.createSkybox) {
  84737. this._skybox.dispose();
  84738. this._skybox = null;
  84739. }
  84740. if (this._skyboxMaterial && !newOptions.createSkybox) {
  84741. this._skyboxMaterial.dispose();
  84742. this._skyboxMaterial = null;
  84743. }
  84744. if (this._skyboxTexture) {
  84745. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  84746. this._skyboxTexture.dispose();
  84747. this._skyboxTexture = null;
  84748. }
  84749. }
  84750. if (this._groundMirror && !newOptions.enableGroundMirror) {
  84751. this._groundMirror.dispose();
  84752. this._groundMirror = null;
  84753. }
  84754. if (this._scene.environmentTexture) {
  84755. if (this._options.environmentTexture != newOptions.environmentTexture) {
  84756. this._scene.environmentTexture.dispose();
  84757. }
  84758. }
  84759. this._options = newOptions;
  84760. this._setupBackground();
  84761. this._setupImageProcessing();
  84762. };
  84763. /**
  84764. * Sets the primary color of all the available elements.
  84765. * @param color
  84766. */
  84767. EnvironmentHelper.prototype.setMainColor = function (color) {
  84768. if (this.groundMaterial) {
  84769. this.groundMaterial.primaryColor = color;
  84770. }
  84771. if (this.skyboxMaterial) {
  84772. this.skyboxMaterial.primaryColor = color;
  84773. }
  84774. if (this.groundMirror) {
  84775. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  84776. }
  84777. };
  84778. /**
  84779. * Setup the image processing according to the specified options.
  84780. */
  84781. EnvironmentHelper.prototype._setupImageProcessing = function () {
  84782. if (this._options.setupImageProcessing) {
  84783. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  84784. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  84785. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  84786. this._setupEnvironmentTexture();
  84787. }
  84788. };
  84789. /**
  84790. * Setup the environment texture according to the specified options.
  84791. */
  84792. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  84793. if (this._scene.environmentTexture) {
  84794. return;
  84795. }
  84796. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  84797. this._scene.environmentTexture = this._options.environmentTexture;
  84798. return;
  84799. }
  84800. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  84801. this._scene.environmentTexture = environmentTexture;
  84802. };
  84803. /**
  84804. * Setup the background according to the specified options.
  84805. */
  84806. EnvironmentHelper.prototype._setupBackground = function () {
  84807. if (!this._rootMesh) {
  84808. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  84809. }
  84810. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  84811. var sceneSize = this._getSceneSize();
  84812. if (this._options.createGround) {
  84813. this._setupGround(sceneSize);
  84814. this._setupGroundMaterial();
  84815. this._setupGroundDiffuseTexture();
  84816. if (this._options.enableGroundMirror) {
  84817. this._setupGroundMirrorTexture(sceneSize);
  84818. }
  84819. this._setupMirrorInGroundMaterial();
  84820. }
  84821. if (this._options.createSkybox) {
  84822. this._setupSkybox(sceneSize);
  84823. this._setupSkyboxMaterial();
  84824. this._setupSkyboxReflectionTexture();
  84825. }
  84826. this._rootMesh.position.x = sceneSize.rootPosition.x;
  84827. this._rootMesh.position.z = sceneSize.rootPosition.z;
  84828. this._rootMesh.position.y = sceneSize.rootPosition.y;
  84829. };
  84830. /**
  84831. * Get the scene sizes according to the setup.
  84832. */
  84833. EnvironmentHelper.prototype._getSceneSize = function () {
  84834. var groundSize = this._options.groundSize;
  84835. var skyboxSize = this._options.skyboxSize;
  84836. var rootPosition = this._options.rootPosition;
  84837. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  84838. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84839. }
  84840. var sceneExtends = this._scene.getWorldExtends();
  84841. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  84842. if (this._options.sizeAuto) {
  84843. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  84844. this._scene.activeCamera.upperRadiusLimit) {
  84845. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  84846. skyboxSize = groundSize;
  84847. }
  84848. var sceneDiagonalLenght = sceneDiagonal.length();
  84849. if (sceneDiagonalLenght > groundSize) {
  84850. groundSize = sceneDiagonalLenght * 2;
  84851. skyboxSize = groundSize;
  84852. }
  84853. // 10 % bigger.
  84854. groundSize *= 1.1;
  84855. skyboxSize *= 1.5;
  84856. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  84857. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  84858. }
  84859. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84860. };
  84861. /**
  84862. * Setup the ground according to the specified options.
  84863. */
  84864. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  84865. var _this = this;
  84866. if (!this._ground) {
  84867. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  84868. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  84869. this._ground.parent = this._rootMesh;
  84870. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  84871. }
  84872. this._ground.receiveShadows = this._options.enableGroundShadow;
  84873. };
  84874. /**
  84875. * Setup the ground material according to the specified options.
  84876. */
  84877. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  84878. if (!this._groundMaterial) {
  84879. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  84880. }
  84881. this._groundMaterial.alpha = this._options.groundOpacity;
  84882. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  84883. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  84884. this._groundMaterial.primaryLevel = 1;
  84885. this._groundMaterial.primaryColor = this._options.groundColor;
  84886. this._groundMaterial.secondaryLevel = 0;
  84887. this._groundMaterial.tertiaryLevel = 0;
  84888. this._groundMaterial.useRGBColor = false;
  84889. this._groundMaterial.enableNoise = true;
  84890. if (this._ground) {
  84891. this._ground.material = this._groundMaterial;
  84892. }
  84893. };
  84894. /**
  84895. * Setup the ground diffuse texture according to the specified options.
  84896. */
  84897. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  84898. if (!this._groundMaterial) {
  84899. return;
  84900. }
  84901. if (this._groundTexture) {
  84902. return;
  84903. }
  84904. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  84905. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  84906. return;
  84907. }
  84908. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  84909. diffuseTexture.gammaSpace = false;
  84910. diffuseTexture.hasAlpha = true;
  84911. this._groundMaterial.diffuseTexture = diffuseTexture;
  84912. };
  84913. /**
  84914. * Setup the ground mirror texture according to the specified options.
  84915. */
  84916. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  84917. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84918. if (!this._groundMirror) {
  84919. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  84920. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  84921. this._groundMirror.anisotropicFilteringLevel = 1;
  84922. this._groundMirror.wrapU = wrapping;
  84923. this._groundMirror.wrapV = wrapping;
  84924. this._groundMirror.gammaSpace = false;
  84925. if (this._groundMirror.renderList) {
  84926. for (var i = 0; i < this._scene.meshes.length; i++) {
  84927. var mesh = this._scene.meshes[i];
  84928. if (mesh !== this._ground &&
  84929. mesh !== this._skybox &&
  84930. mesh !== this._rootMesh) {
  84931. this._groundMirror.renderList.push(mesh);
  84932. }
  84933. }
  84934. }
  84935. }
  84936. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  84937. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  84938. };
  84939. /**
  84940. * Setup the ground to receive the mirror texture.
  84941. */
  84942. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  84943. if (this._groundMaterial) {
  84944. this._groundMaterial.reflectionTexture = this._groundMirror;
  84945. this._groundMaterial.reflectionFresnel = true;
  84946. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  84947. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  84948. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  84949. }
  84950. };
  84951. /**
  84952. * Setup the skybox according to the specified options.
  84953. */
  84954. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  84955. var _this = this;
  84956. if (!this._skybox) {
  84957. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  84958. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  84959. }
  84960. this._skybox.parent = this._rootMesh;
  84961. };
  84962. /**
  84963. * Setup the skybox material according to the specified options.
  84964. */
  84965. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  84966. if (!this._skybox) {
  84967. return;
  84968. }
  84969. if (!this._skyboxMaterial) {
  84970. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  84971. }
  84972. this._skyboxMaterial.useRGBColor = false;
  84973. this._skyboxMaterial.primaryLevel = 1;
  84974. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  84975. this._skyboxMaterial.secondaryLevel = 0;
  84976. this._skyboxMaterial.tertiaryLevel = 0;
  84977. this._skyboxMaterial.enableNoise = true;
  84978. this._skybox.material = this._skyboxMaterial;
  84979. };
  84980. /**
  84981. * Setup the skybox reflection texture according to the specified options.
  84982. */
  84983. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  84984. if (!this._skyboxMaterial) {
  84985. return;
  84986. }
  84987. if (this._skyboxTexture) {
  84988. return;
  84989. }
  84990. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  84991. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84992. return;
  84993. }
  84994. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  84995. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  84996. this._skyboxTexture.gammaSpace = false;
  84997. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84998. };
  84999. /**
  85000. * Dispose all the elements created by the Helper.
  85001. */
  85002. EnvironmentHelper.prototype.dispose = function () {
  85003. if (this._groundMaterial) {
  85004. this._groundMaterial.dispose(true, true);
  85005. }
  85006. if (this._skyboxMaterial) {
  85007. this._skyboxMaterial.dispose(true, true);
  85008. }
  85009. this._rootMesh.dispose(false);
  85010. };
  85011. /**
  85012. * Default ground texture URL.
  85013. */
  85014. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  85015. /**
  85016. * Default skybox texture URL.
  85017. */
  85018. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  85019. /**
  85020. * Default environment texture URL.
  85021. */
  85022. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  85023. return EnvironmentHelper;
  85024. }());
  85025. BABYLON.EnvironmentHelper = EnvironmentHelper;
  85026. })(BABYLON || (BABYLON = {}));
  85027. //# sourceMappingURL=babylon.environmentHelper.js.map
  85028. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,coc,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec4 blurred=texture2D(textureSampler,vUV);\nvec4 original=texture2D(originalSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\ngl_FragColor=mix(original,blurred,coc);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D depthSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  85029. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nlightingInfo computeProjectionTexture(lightingInfo origin,sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nlightingInfo result=origin;\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec4 textureColor=texture2D(projectionLightSampler,strq.xy);\nresult.diffuse*=vec3(textureColor);\nreturn result;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#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#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo=computeProjectionTexture(info,projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#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 DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  85030. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85031. var BABYLON;
  85032. (function (BABYLON) {
  85033. var GridMaterialDefines = /** @class */ (function (_super) {
  85034. __extends(GridMaterialDefines, _super);
  85035. function GridMaterialDefines() {
  85036. var _this = _super.call(this) || this;
  85037. _this.TRANSPARENT = false;
  85038. _this.FOG = false;
  85039. _this.PREMULTIPLYALPHA = false;
  85040. _this.rebuild();
  85041. return _this;
  85042. }
  85043. return GridMaterialDefines;
  85044. }(BABYLON.MaterialDefines));
  85045. /**
  85046. * The grid materials allows you to wrap any shape with a grid.
  85047. * Colors are customizable.
  85048. */
  85049. var GridMaterial = /** @class */ (function (_super) {
  85050. __extends(GridMaterial, _super);
  85051. /**
  85052. * constructor
  85053. * @param name The name given to the material in order to identify it afterwards.
  85054. * @param scene The scene the material is used in.
  85055. */
  85056. function GridMaterial(name, scene) {
  85057. var _this = _super.call(this, name, scene) || this;
  85058. /**
  85059. * Main color of the grid (e.g. between lines)
  85060. */
  85061. _this.mainColor = BABYLON.Color3.Black();
  85062. /**
  85063. * Color of the grid lines.
  85064. */
  85065. _this.lineColor = BABYLON.Color3.Teal();
  85066. /**
  85067. * The scale of the grid compared to unit.
  85068. */
  85069. _this.gridRatio = 1.0;
  85070. /**
  85071. * Allows setting an offset for the grid lines.
  85072. */
  85073. _this.gridOffset = BABYLON.Vector3.Zero();
  85074. /**
  85075. * The frequency of thicker lines.
  85076. */
  85077. _this.majorUnitFrequency = 10;
  85078. /**
  85079. * The visibility of minor units in the grid.
  85080. */
  85081. _this.minorUnitVisibility = 0.33;
  85082. /**
  85083. * The grid opacity outside of the lines.
  85084. */
  85085. _this.opacity = 1.0;
  85086. /**
  85087. * Determine RBG output is premultiplied by alpha value.
  85088. */
  85089. _this.preMultiplyAlpha = false;
  85090. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  85091. return _this;
  85092. }
  85093. /**
  85094. * Returns wehter or not the grid requires alpha blending.
  85095. */
  85096. GridMaterial.prototype.needAlphaBlending = function () {
  85097. return this.opacity < 1.0;
  85098. };
  85099. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  85100. return this.needAlphaBlending();
  85101. };
  85102. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  85103. if (this.isFrozen) {
  85104. if (this._wasPreviouslyReady && subMesh.effect) {
  85105. return true;
  85106. }
  85107. }
  85108. if (!subMesh._materialDefines) {
  85109. subMesh._materialDefines = new GridMaterialDefines();
  85110. }
  85111. var defines = subMesh._materialDefines;
  85112. var scene = this.getScene();
  85113. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  85114. if (this._renderId === scene.getRenderId()) {
  85115. return true;
  85116. }
  85117. }
  85118. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  85119. defines.TRANSPARENT = !defines.TRANSPARENT;
  85120. defines.markAsUnprocessed();
  85121. }
  85122. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  85123. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  85124. defines.markAsUnprocessed();
  85125. }
  85126. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  85127. // Get correct effect
  85128. if (defines.isDirty) {
  85129. defines.markAsProcessed();
  85130. scene.resetCachedMaterial();
  85131. // Attributes
  85132. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85133. // Defines
  85134. var join = defines.toString();
  85135. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  85136. }
  85137. if (!subMesh.effect || !subMesh.effect.isReady()) {
  85138. return false;
  85139. }
  85140. this._renderId = scene.getRenderId();
  85141. this._wasPreviouslyReady = true;
  85142. return true;
  85143. };
  85144. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  85145. var scene = this.getScene();
  85146. var defines = subMesh._materialDefines;
  85147. if (!defines) {
  85148. return;
  85149. }
  85150. var effect = subMesh.effect;
  85151. if (!effect) {
  85152. return;
  85153. }
  85154. this._activeEffect = effect;
  85155. // Matrices
  85156. this.bindOnlyWorldMatrix(world);
  85157. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  85158. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  85159. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  85160. // Uniforms
  85161. if (this._mustRebind(scene, effect)) {
  85162. this._activeEffect.setColor3("mainColor", this.mainColor);
  85163. this._activeEffect.setColor3("lineColor", this.lineColor);
  85164. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  85165. this._gridControl.x = this.gridRatio;
  85166. this._gridControl.y = Math.round(this.majorUnitFrequency);
  85167. this._gridControl.z = this.minorUnitVisibility;
  85168. this._gridControl.w = this.opacity;
  85169. this._activeEffect.setVector4("gridControl", this._gridControl);
  85170. }
  85171. // Fog
  85172. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  85173. this._afterBind(mesh, this._activeEffect);
  85174. };
  85175. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  85176. _super.prototype.dispose.call(this, forceDisposeEffect);
  85177. };
  85178. GridMaterial.prototype.clone = function (name) {
  85179. var _this = this;
  85180. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  85181. };
  85182. GridMaterial.prototype.serialize = function () {
  85183. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85184. serializationObject.customType = "BABYLON.GridMaterial";
  85185. return serializationObject;
  85186. };
  85187. GridMaterial.prototype.getClassName = function () {
  85188. return "GridMaterial";
  85189. };
  85190. GridMaterial.Parse = function (source, scene, rootUrl) {
  85191. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  85192. };
  85193. __decorate([
  85194. BABYLON.serializeAsColor3()
  85195. ], GridMaterial.prototype, "mainColor", void 0);
  85196. __decorate([
  85197. BABYLON.serializeAsColor3()
  85198. ], GridMaterial.prototype, "lineColor", void 0);
  85199. __decorate([
  85200. BABYLON.serialize()
  85201. ], GridMaterial.prototype, "gridRatio", void 0);
  85202. __decorate([
  85203. BABYLON.serializeAsColor3()
  85204. ], GridMaterial.prototype, "gridOffset", void 0);
  85205. __decorate([
  85206. BABYLON.serialize()
  85207. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  85208. __decorate([
  85209. BABYLON.serialize()
  85210. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  85211. __decorate([
  85212. BABYLON.serialize()
  85213. ], GridMaterial.prototype, "opacity", void 0);
  85214. __decorate([
  85215. BABYLON.serialize()
  85216. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  85217. return GridMaterial;
  85218. }(BABYLON.PushMaterial));
  85219. BABYLON.GridMaterial = GridMaterial;
  85220. })(BABYLON || (BABYLON = {}));
  85221. //# sourceMappingURL=babylon.gridmaterial.js.map
  85222. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  85223. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  85224. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  85225. var BABYLON;
  85226. (function (BABYLON) {
  85227. var GLTFLoaderCoordinateSystemMode;
  85228. (function (GLTFLoaderCoordinateSystemMode) {
  85229. /**
  85230. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  85231. */
  85232. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  85233. /**
  85234. * Sets the useRightHandedSystem flag on the scene.
  85235. */
  85236. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  85237. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  85238. var GLTFLoaderAnimationStartMode;
  85239. (function (GLTFLoaderAnimationStartMode) {
  85240. /**
  85241. * No animation will start.
  85242. */
  85243. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  85244. /**
  85245. * The first animation will start.
  85246. */
  85247. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  85248. /**
  85249. * All animations will start.
  85250. */
  85251. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  85252. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  85253. var GLTFFileLoader = /** @class */ (function () {
  85254. function GLTFFileLoader() {
  85255. // #region Common options
  85256. /**
  85257. * Raised when the asset has been parsed.
  85258. * The data.json property stores the glTF JSON.
  85259. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  85260. */
  85261. this.onParsedObservable = new BABYLON.Observable();
  85262. // #endregion
  85263. // #region V2 options
  85264. /**
  85265. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  85266. */
  85267. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  85268. /**
  85269. * The animation start mode (NONE, FIRST, ALL).
  85270. */
  85271. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  85272. /**
  85273. * Set to true to compile materials before raising the success callback.
  85274. */
  85275. this.compileMaterials = false;
  85276. /**
  85277. * Set to true to also compile materials with clip planes.
  85278. */
  85279. this.useClipPlane = false;
  85280. /**
  85281. * Set to true to compile shadow generators before raising the success callback.
  85282. */
  85283. this.compileShadowGenerators = false;
  85284. /**
  85285. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  85286. */
  85287. this.onMeshLoadedObservable = new BABYLON.Observable();
  85288. /**
  85289. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  85290. */
  85291. this.onTextureLoadedObservable = new BABYLON.Observable();
  85292. /**
  85293. * Raised when the loader creates a material after parsing the glTF properties of the material.
  85294. */
  85295. this.onMaterialLoadedObservable = new BABYLON.Observable();
  85296. /**
  85297. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  85298. * For assets with LODs, raised when all of the LODs are complete.
  85299. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  85300. */
  85301. this.onCompleteObservable = new BABYLON.Observable();
  85302. /**
  85303. * Raised when the loader is disposed.
  85304. */
  85305. this.onDisposeObservable = new BABYLON.Observable();
  85306. // #endregion
  85307. this._loader = null;
  85308. this.name = "gltf";
  85309. this.extensions = {
  85310. ".gltf": { isBinary: false },
  85311. ".glb": { isBinary: true }
  85312. };
  85313. }
  85314. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  85315. set: function (callback) {
  85316. if (this._onParsedObserver) {
  85317. this.onParsedObservable.remove(this._onParsedObserver);
  85318. }
  85319. this._onParsedObserver = this.onParsedObservable.add(callback);
  85320. },
  85321. enumerable: true,
  85322. configurable: true
  85323. });
  85324. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  85325. set: function (callback) {
  85326. if (this._onMeshLoadedObserver) {
  85327. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  85328. }
  85329. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  85330. },
  85331. enumerable: true,
  85332. configurable: true
  85333. });
  85334. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  85335. set: function (callback) {
  85336. if (this._onTextureLoadedObserver) {
  85337. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  85338. }
  85339. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  85340. },
  85341. enumerable: true,
  85342. configurable: true
  85343. });
  85344. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  85345. set: function (callback) {
  85346. if (this._onMaterialLoadedObserver) {
  85347. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  85348. }
  85349. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  85350. },
  85351. enumerable: true,
  85352. configurable: true
  85353. });
  85354. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  85355. set: function (callback) {
  85356. if (this._onCompleteObserver) {
  85357. this.onCompleteObservable.remove(this._onCompleteObserver);
  85358. }
  85359. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  85360. },
  85361. enumerable: true,
  85362. configurable: true
  85363. });
  85364. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  85365. set: function (callback) {
  85366. if (this._onDisposeObserver) {
  85367. this.onDisposeObservable.remove(this._onDisposeObserver);
  85368. }
  85369. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  85370. },
  85371. enumerable: true,
  85372. configurable: true
  85373. });
  85374. /**
  85375. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  85376. */
  85377. GLTFFileLoader.prototype.dispose = function () {
  85378. if (this._loader) {
  85379. this._loader.dispose();
  85380. this._loader = null;
  85381. }
  85382. this.onParsedObservable.clear();
  85383. this.onMeshLoadedObservable.clear();
  85384. this.onTextureLoadedObservable.clear();
  85385. this.onMaterialLoadedObservable.clear();
  85386. this.onCompleteObservable.clear();
  85387. this.onDisposeObservable.notifyObservers(this);
  85388. this.onDisposeObservable.clear();
  85389. };
  85390. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  85391. try {
  85392. var loaderData = this._parse(data);
  85393. this._loader = this._getLoader(loaderData);
  85394. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85395. }
  85396. catch (e) {
  85397. if (onError) {
  85398. onError(e.message, e);
  85399. }
  85400. else {
  85401. BABYLON.Tools.Error(e.message);
  85402. }
  85403. }
  85404. };
  85405. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85406. try {
  85407. var loaderData = this._parse(data);
  85408. this._loader = this._getLoader(loaderData);
  85409. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  85410. }
  85411. catch (e) {
  85412. if (onError) {
  85413. onError(e.message, e);
  85414. }
  85415. else {
  85416. BABYLON.Tools.Error(e.message);
  85417. }
  85418. }
  85419. };
  85420. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85421. try {
  85422. var loaderData = this._parse(data);
  85423. this._loader = this._getLoader(loaderData);
  85424. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  85425. var container = new BABYLON.AssetContainer(scene);
  85426. Array.prototype.push.apply(container.meshes, meshes);
  85427. Array.prototype.push.apply(container.particleSystems, particleSystems);
  85428. Array.prototype.push.apply(container.skeletons, skeletons);
  85429. container.removeAllFromScene();
  85430. onSuccess(container);
  85431. }, onProgress, onError);
  85432. }
  85433. catch (e) {
  85434. if (onError) {
  85435. onError(e.message, e);
  85436. }
  85437. else {
  85438. BABYLON.Tools.Error(e.message);
  85439. }
  85440. }
  85441. };
  85442. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  85443. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  85444. };
  85445. GLTFFileLoader.prototype.createPlugin = function () {
  85446. return new GLTFFileLoader();
  85447. };
  85448. GLTFFileLoader.prototype._parse = function (data) {
  85449. var parsedData;
  85450. if (data instanceof ArrayBuffer) {
  85451. parsedData = GLTFFileLoader._parseBinary(data);
  85452. }
  85453. else {
  85454. parsedData = {
  85455. json: JSON.parse(data),
  85456. bin: null
  85457. };
  85458. }
  85459. this.onParsedObservable.notifyObservers(parsedData);
  85460. return parsedData;
  85461. };
  85462. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  85463. var _this = this;
  85464. var loaderVersion = { major: 2, minor: 0 };
  85465. var asset = loaderData.json.asset || {};
  85466. var version = GLTFFileLoader._parseVersion(asset.version);
  85467. if (!version) {
  85468. throw new Error("Invalid version: " + asset.version);
  85469. }
  85470. if (asset.minVersion !== undefined) {
  85471. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  85472. if (!minVersion) {
  85473. throw new Error("Invalid minimum version: " + asset.minVersion);
  85474. }
  85475. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  85476. throw new Error("Incompatible minimum version: " + asset.minVersion);
  85477. }
  85478. }
  85479. var createLoaders = {
  85480. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  85481. 2: GLTFFileLoader.CreateGLTFLoaderV2
  85482. };
  85483. var createLoader = createLoaders[version.major];
  85484. if (!createLoader) {
  85485. throw new Error("Unsupported version: " + asset.version);
  85486. }
  85487. var loader = createLoader();
  85488. loader.coordinateSystemMode = this.coordinateSystemMode;
  85489. loader.animationStartMode = this.animationStartMode;
  85490. loader.compileMaterials = this.compileMaterials;
  85491. loader.useClipPlane = this.useClipPlane;
  85492. loader.compileShadowGenerators = this.compileShadowGenerators;
  85493. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  85494. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  85495. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  85496. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  85497. return loader;
  85498. };
  85499. GLTFFileLoader._parseBinary = function (data) {
  85500. var Binary = {
  85501. Magic: 0x46546C67
  85502. };
  85503. var binaryReader = new BinaryReader(data);
  85504. var magic = binaryReader.readUint32();
  85505. if (magic !== Binary.Magic) {
  85506. throw new Error("Unexpected magic: " + magic);
  85507. }
  85508. var version = binaryReader.readUint32();
  85509. switch (version) {
  85510. case 1: return GLTFFileLoader._parseV1(binaryReader);
  85511. case 2: return GLTFFileLoader._parseV2(binaryReader);
  85512. }
  85513. throw new Error("Unsupported version: " + version);
  85514. };
  85515. GLTFFileLoader._parseV1 = function (binaryReader) {
  85516. var ContentFormat = {
  85517. JSON: 0
  85518. };
  85519. var length = binaryReader.readUint32();
  85520. if (length != binaryReader.getLength()) {
  85521. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85522. }
  85523. var contentLength = binaryReader.readUint32();
  85524. var contentFormat = binaryReader.readUint32();
  85525. var content;
  85526. switch (contentFormat) {
  85527. case ContentFormat.JSON: {
  85528. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  85529. break;
  85530. }
  85531. default: {
  85532. throw new Error("Unexpected content format: " + contentFormat);
  85533. }
  85534. }
  85535. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  85536. var body = binaryReader.readUint8Array(bytesRemaining);
  85537. return {
  85538. json: content,
  85539. bin: body
  85540. };
  85541. };
  85542. GLTFFileLoader._parseV2 = function (binaryReader) {
  85543. var ChunkFormat = {
  85544. JSON: 0x4E4F534A,
  85545. BIN: 0x004E4942
  85546. };
  85547. var length = binaryReader.readUint32();
  85548. if (length !== binaryReader.getLength()) {
  85549. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  85550. }
  85551. // JSON chunk
  85552. var chunkLength = binaryReader.readUint32();
  85553. var chunkFormat = binaryReader.readUint32();
  85554. if (chunkFormat !== ChunkFormat.JSON) {
  85555. throw new Error("First chunk format is not JSON");
  85556. }
  85557. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  85558. // Look for BIN chunk
  85559. var bin = null;
  85560. while (binaryReader.getPosition() < binaryReader.getLength()) {
  85561. var chunkLength_1 = binaryReader.readUint32();
  85562. var chunkFormat_1 = binaryReader.readUint32();
  85563. switch (chunkFormat_1) {
  85564. case ChunkFormat.JSON: {
  85565. throw new Error("Unexpected JSON chunk");
  85566. }
  85567. case ChunkFormat.BIN: {
  85568. bin = binaryReader.readUint8Array(chunkLength_1);
  85569. break;
  85570. }
  85571. default: {
  85572. // ignore unrecognized chunkFormat
  85573. binaryReader.skipBytes(chunkLength_1);
  85574. break;
  85575. }
  85576. }
  85577. }
  85578. return {
  85579. json: json,
  85580. bin: bin
  85581. };
  85582. };
  85583. GLTFFileLoader._parseVersion = function (version) {
  85584. if (version === "1.0" || version === "1.0.1") {
  85585. return {
  85586. major: 1,
  85587. minor: 0
  85588. };
  85589. }
  85590. var match = (version + "").match(/^(\d+)\.(\d+)/);
  85591. if (!match) {
  85592. return null;
  85593. }
  85594. return {
  85595. major: parseInt(match[1]),
  85596. minor: parseInt(match[2])
  85597. };
  85598. };
  85599. GLTFFileLoader._compareVersion = function (a, b) {
  85600. if (a.major > b.major)
  85601. return 1;
  85602. if (a.major < b.major)
  85603. return -1;
  85604. if (a.minor > b.minor)
  85605. return 1;
  85606. if (a.minor < b.minor)
  85607. return -1;
  85608. return 0;
  85609. };
  85610. GLTFFileLoader._decodeBufferToText = function (buffer) {
  85611. var result = "";
  85612. var length = buffer.byteLength;
  85613. for (var i = 0; i < length; i++) {
  85614. result += String.fromCharCode(buffer[i]);
  85615. }
  85616. return result;
  85617. };
  85618. // #endregion
  85619. // #region V1 options
  85620. GLTFFileLoader.IncrementalLoading = true;
  85621. GLTFFileLoader.HomogeneousCoordinates = false;
  85622. return GLTFFileLoader;
  85623. }());
  85624. BABYLON.GLTFFileLoader = GLTFFileLoader;
  85625. var BinaryReader = /** @class */ (function () {
  85626. function BinaryReader(arrayBuffer) {
  85627. this._arrayBuffer = arrayBuffer;
  85628. this._dataView = new DataView(arrayBuffer);
  85629. this._byteOffset = 0;
  85630. }
  85631. BinaryReader.prototype.getPosition = function () {
  85632. return this._byteOffset;
  85633. };
  85634. BinaryReader.prototype.getLength = function () {
  85635. return this._arrayBuffer.byteLength;
  85636. };
  85637. BinaryReader.prototype.readUint32 = function () {
  85638. var value = this._dataView.getUint32(this._byteOffset, true);
  85639. this._byteOffset += 4;
  85640. return value;
  85641. };
  85642. BinaryReader.prototype.readUint8Array = function (length) {
  85643. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  85644. this._byteOffset += length;
  85645. return value;
  85646. };
  85647. BinaryReader.prototype.skipBytes = function (length) {
  85648. this._byteOffset += length;
  85649. };
  85650. return BinaryReader;
  85651. }());
  85652. if (BABYLON.SceneLoader) {
  85653. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  85654. }
  85655. })(BABYLON || (BABYLON = {}));
  85656. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  85657. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85658. var BABYLON;
  85659. (function (BABYLON) {
  85660. var GLTF1;
  85661. (function (GLTF1) {
  85662. /**
  85663. * Enums
  85664. */
  85665. var EComponentType;
  85666. (function (EComponentType) {
  85667. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  85668. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  85669. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  85670. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  85671. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  85672. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  85673. var EShaderType;
  85674. (function (EShaderType) {
  85675. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  85676. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  85677. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  85678. var EParameterType;
  85679. (function (EParameterType) {
  85680. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  85681. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  85682. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  85683. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  85684. EParameterType[EParameterType["INT"] = 5124] = "INT";
  85685. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  85686. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  85687. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  85688. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  85689. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  85690. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  85691. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  85692. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  85693. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  85694. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  85695. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  85696. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  85697. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  85698. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  85699. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  85700. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  85701. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  85702. var ETextureWrapMode;
  85703. (function (ETextureWrapMode) {
  85704. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  85705. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  85706. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  85707. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  85708. var ETextureFilterType;
  85709. (function (ETextureFilterType) {
  85710. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  85711. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  85712. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  85713. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  85714. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  85715. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  85716. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  85717. var ETextureFormat;
  85718. (function (ETextureFormat) {
  85719. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  85720. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  85721. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  85722. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  85723. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  85724. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  85725. var ECullingType;
  85726. (function (ECullingType) {
  85727. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  85728. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  85729. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  85730. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  85731. var EBlendingFunction;
  85732. (function (EBlendingFunction) {
  85733. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  85734. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  85735. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  85736. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  85737. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  85738. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  85739. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  85740. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  85741. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  85742. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  85743. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  85744. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  85745. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  85746. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  85747. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  85748. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  85749. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  85750. })(BABYLON || (BABYLON = {}));
  85751. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  85752. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85753. var BABYLON;
  85754. (function (BABYLON) {
  85755. var GLTF1;
  85756. (function (GLTF1) {
  85757. /**
  85758. * Tokenizer. Used for shaders compatibility
  85759. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  85760. */
  85761. var ETokenType;
  85762. (function (ETokenType) {
  85763. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  85764. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  85765. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  85766. })(ETokenType || (ETokenType = {}));
  85767. var Tokenizer = /** @class */ (function () {
  85768. function Tokenizer(toParse) {
  85769. this._pos = 0;
  85770. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  85771. this._toParse = toParse;
  85772. this._maxPos = toParse.length;
  85773. }
  85774. Tokenizer.prototype.getNextToken = function () {
  85775. if (this.isEnd())
  85776. return ETokenType.END_OF_INPUT;
  85777. this.currentString = this.read();
  85778. this.currentToken = ETokenType.UNKNOWN;
  85779. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  85780. this.currentToken = ETokenType.IDENTIFIER;
  85781. this.currentIdentifier = this.currentString;
  85782. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  85783. this.currentIdentifier += this.currentString;
  85784. this.forward();
  85785. }
  85786. }
  85787. return this.currentToken;
  85788. };
  85789. Tokenizer.prototype.peek = function () {
  85790. return this._toParse[this._pos];
  85791. };
  85792. Tokenizer.prototype.read = function () {
  85793. return this._toParse[this._pos++];
  85794. };
  85795. Tokenizer.prototype.forward = function () {
  85796. this._pos++;
  85797. };
  85798. Tokenizer.prototype.isEnd = function () {
  85799. return this._pos >= this._maxPos;
  85800. };
  85801. return Tokenizer;
  85802. }());
  85803. /**
  85804. * Values
  85805. */
  85806. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  85807. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  85808. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  85809. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  85810. /**
  85811. * Parse
  85812. */
  85813. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  85814. for (var buf in parsedBuffers) {
  85815. var parsedBuffer = parsedBuffers[buf];
  85816. gltfRuntime.buffers[buf] = parsedBuffer;
  85817. gltfRuntime.buffersCount++;
  85818. }
  85819. };
  85820. var parseShaders = function (parsedShaders, gltfRuntime) {
  85821. for (var sha in parsedShaders) {
  85822. var parsedShader = parsedShaders[sha];
  85823. gltfRuntime.shaders[sha] = parsedShader;
  85824. gltfRuntime.shaderscount++;
  85825. }
  85826. };
  85827. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  85828. for (var object in parsedObjects) {
  85829. var parsedObject = parsedObjects[object];
  85830. gltfRuntime[runtimeProperty][object] = parsedObject;
  85831. }
  85832. };
  85833. /**
  85834. * Utils
  85835. */
  85836. var normalizeUVs = function (buffer) {
  85837. if (!buffer) {
  85838. return;
  85839. }
  85840. for (var i = 0; i < buffer.length / 2; i++) {
  85841. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  85842. }
  85843. };
  85844. var getAttribute = function (attributeParameter) {
  85845. if (attributeParameter.semantic === "NORMAL") {
  85846. return "normal";
  85847. }
  85848. else if (attributeParameter.semantic === "POSITION") {
  85849. return "position";
  85850. }
  85851. else if (attributeParameter.semantic === "JOINT") {
  85852. return "matricesIndices";
  85853. }
  85854. else if (attributeParameter.semantic === "WEIGHT") {
  85855. return "matricesWeights";
  85856. }
  85857. else if (attributeParameter.semantic === "COLOR") {
  85858. return "color";
  85859. }
  85860. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  85861. var channel = Number(attributeParameter.semantic.split("_")[1]);
  85862. return "uv" + (channel === 0 ? "" : channel + 1);
  85863. }
  85864. return null;
  85865. };
  85866. /**
  85867. * Loads and creates animations
  85868. */
  85869. var loadAnimations = function (gltfRuntime) {
  85870. for (var anim in gltfRuntime.animations) {
  85871. var animation = gltfRuntime.animations[anim];
  85872. if (!animation.channels || !animation.samplers) {
  85873. continue;
  85874. }
  85875. var lastAnimation = null;
  85876. for (var i = 0; i < animation.channels.length; i++) {
  85877. // Get parameters and load buffers
  85878. var channel = animation.channels[i];
  85879. var sampler = animation.samplers[channel.sampler];
  85880. if (!sampler) {
  85881. continue;
  85882. }
  85883. var inputData = null;
  85884. var outputData = null;
  85885. if (animation.parameters) {
  85886. inputData = animation.parameters[sampler.input];
  85887. outputData = animation.parameters[sampler.output];
  85888. }
  85889. else {
  85890. inputData = sampler.input;
  85891. outputData = sampler.output;
  85892. }
  85893. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  85894. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  85895. var targetID = channel.target.id;
  85896. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  85897. if (targetNode === null) {
  85898. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  85899. }
  85900. if (targetNode === null) {
  85901. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  85902. continue;
  85903. }
  85904. var isBone = targetNode instanceof BABYLON.Bone;
  85905. // Get target path (position, rotation or scaling)
  85906. var targetPath = channel.target.path;
  85907. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  85908. if (targetPathIndex !== -1) {
  85909. targetPath = babylonAnimationPaths[targetPathIndex];
  85910. }
  85911. // Determine animation type
  85912. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  85913. if (!isBone) {
  85914. if (targetPath === "rotationQuaternion") {
  85915. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  85916. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  85917. }
  85918. else {
  85919. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85920. }
  85921. }
  85922. // Create animation and key frames
  85923. var babylonAnimation = null;
  85924. var keys = [];
  85925. var arrayOffset = 0;
  85926. var modifyKey = false;
  85927. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  85928. babylonAnimation = lastAnimation;
  85929. modifyKey = true;
  85930. }
  85931. if (!modifyKey) {
  85932. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  85933. }
  85934. // For each frame
  85935. for (var j = 0; j < bufferInput.length; j++) {
  85936. var value = null;
  85937. if (targetPath === "rotationQuaternion") {
  85938. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  85939. arrayOffset += 4;
  85940. }
  85941. else {
  85942. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  85943. arrayOffset += 3;
  85944. }
  85945. if (isBone) {
  85946. var bone = targetNode;
  85947. var translation = BABYLON.Vector3.Zero();
  85948. var rotationQuaternion = new BABYLON.Quaternion();
  85949. var scaling = BABYLON.Vector3.Zero();
  85950. // Warning on decompose
  85951. var mat = bone.getBaseMatrix();
  85952. if (modifyKey && lastAnimation) {
  85953. mat = lastAnimation.getKeys()[j].value;
  85954. }
  85955. mat.decompose(scaling, rotationQuaternion, translation);
  85956. if (targetPath === "position") {
  85957. translation = value;
  85958. }
  85959. else if (targetPath === "rotationQuaternion") {
  85960. rotationQuaternion = value;
  85961. }
  85962. else {
  85963. scaling = value;
  85964. }
  85965. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  85966. }
  85967. if (!modifyKey) {
  85968. keys.push({
  85969. frame: bufferInput[j],
  85970. value: value
  85971. });
  85972. }
  85973. else if (lastAnimation) {
  85974. lastAnimation.getKeys()[j].value = value;
  85975. }
  85976. }
  85977. // Finish
  85978. if (!modifyKey && babylonAnimation) {
  85979. babylonAnimation.setKeys(keys);
  85980. targetNode.animations.push(babylonAnimation);
  85981. }
  85982. lastAnimation = babylonAnimation;
  85983. gltfRuntime.scene.stopAnimation(targetNode);
  85984. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  85985. }
  85986. }
  85987. };
  85988. /**
  85989. * Returns the bones transformation matrix
  85990. */
  85991. var configureBoneTransformation = function (node) {
  85992. var mat = null;
  85993. if (node.translation || node.rotation || node.scale) {
  85994. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  85995. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  85996. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  85997. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  85998. }
  85999. else {
  86000. mat = BABYLON.Matrix.FromArray(node.matrix);
  86001. }
  86002. return mat;
  86003. };
  86004. /**
  86005. * Returns the parent bone
  86006. */
  86007. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  86008. // Try to find
  86009. for (var i = 0; i < newSkeleton.bones.length; i++) {
  86010. if (newSkeleton.bones[i].name === jointName) {
  86011. return newSkeleton.bones[i];
  86012. }
  86013. }
  86014. // Not found, search in gltf nodes
  86015. var nodes = gltfRuntime.nodes;
  86016. for (var nde in nodes) {
  86017. var node = nodes[nde];
  86018. if (!node.jointName) {
  86019. continue;
  86020. }
  86021. var children = node.children;
  86022. for (var i = 0; i < children.length; i++) {
  86023. var child = gltfRuntime.nodes[children[i]];
  86024. if (!child.jointName) {
  86025. continue;
  86026. }
  86027. if (child.jointName === jointName) {
  86028. var mat = configureBoneTransformation(node);
  86029. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  86030. bone.id = nde;
  86031. return bone;
  86032. }
  86033. }
  86034. }
  86035. return null;
  86036. };
  86037. /**
  86038. * Returns the appropriate root node
  86039. */
  86040. var getNodeToRoot = function (nodesToRoot, id) {
  86041. for (var i = 0; i < nodesToRoot.length; i++) {
  86042. var nodeToRoot = nodesToRoot[i];
  86043. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  86044. var child = nodeToRoot.node.children[j];
  86045. if (child === id) {
  86046. return nodeToRoot.bone;
  86047. }
  86048. }
  86049. }
  86050. return null;
  86051. };
  86052. /**
  86053. * Returns the node with the joint name
  86054. */
  86055. var getJointNode = function (gltfRuntime, jointName) {
  86056. var nodes = gltfRuntime.nodes;
  86057. var node = nodes[jointName];
  86058. if (node) {
  86059. return {
  86060. node: node,
  86061. id: jointName
  86062. };
  86063. }
  86064. for (var nde in nodes) {
  86065. node = nodes[nde];
  86066. if (node.jointName === jointName) {
  86067. return {
  86068. node: node,
  86069. id: nde
  86070. };
  86071. }
  86072. }
  86073. return null;
  86074. };
  86075. /**
  86076. * Checks if a nodes is in joints
  86077. */
  86078. var nodeIsInJoints = function (skins, id) {
  86079. for (var i = 0; i < skins.jointNames.length; i++) {
  86080. if (skins.jointNames[i] === id) {
  86081. return true;
  86082. }
  86083. }
  86084. return false;
  86085. };
  86086. /**
  86087. * Fills the nodes to root for bones and builds hierarchy
  86088. */
  86089. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  86090. // Creates nodes for root
  86091. for (var nde in gltfRuntime.nodes) {
  86092. var node = gltfRuntime.nodes[nde];
  86093. var id = nde;
  86094. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  86095. continue;
  86096. }
  86097. // Create node to root bone
  86098. var mat = configureBoneTransformation(node);
  86099. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  86100. bone.id = id;
  86101. nodesToRoot.push({ bone: bone, node: node, id: id });
  86102. }
  86103. // Parenting
  86104. for (var i = 0; i < nodesToRoot.length; i++) {
  86105. var nodeToRoot = nodesToRoot[i];
  86106. var children = nodeToRoot.node.children;
  86107. for (var j = 0; j < children.length; j++) {
  86108. var child = null;
  86109. for (var k = 0; k < nodesToRoot.length; k++) {
  86110. if (nodesToRoot[k].id === children[j]) {
  86111. child = nodesToRoot[k];
  86112. break;
  86113. }
  86114. }
  86115. if (child) {
  86116. child.bone._parent = nodeToRoot.bone;
  86117. nodeToRoot.bone.children.push(child.bone);
  86118. }
  86119. }
  86120. }
  86121. };
  86122. /**
  86123. * Imports a skeleton
  86124. */
  86125. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  86126. if (!newSkeleton) {
  86127. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  86128. }
  86129. if (!skins.babylonSkeleton) {
  86130. return newSkeleton;
  86131. }
  86132. // Find the root bones
  86133. var nodesToRoot = [];
  86134. var nodesToRootToAdd = [];
  86135. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  86136. newSkeleton.bones = [];
  86137. // Joints
  86138. for (var i = 0; i < skins.jointNames.length; i++) {
  86139. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86140. if (!jointNode) {
  86141. continue;
  86142. }
  86143. var node = jointNode.node;
  86144. if (!node) {
  86145. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  86146. continue;
  86147. }
  86148. var id = jointNode.id;
  86149. // Optimize, if the bone already exists...
  86150. var existingBone = gltfRuntime.scene.getBoneByID(id);
  86151. if (existingBone) {
  86152. newSkeleton.bones.push(existingBone);
  86153. continue;
  86154. }
  86155. // Search for parent bone
  86156. var foundBone = false;
  86157. var parentBone = null;
  86158. for (var j = 0; j < i; j++) {
  86159. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  86160. if (!jointNode_1) {
  86161. continue;
  86162. }
  86163. var joint = jointNode_1.node;
  86164. if (!joint) {
  86165. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  86166. continue;
  86167. }
  86168. var children = joint.children;
  86169. if (!children) {
  86170. continue;
  86171. }
  86172. foundBone = false;
  86173. for (var k = 0; k < children.length; k++) {
  86174. if (children[k] === id) {
  86175. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  86176. foundBone = true;
  86177. break;
  86178. }
  86179. }
  86180. if (foundBone) {
  86181. break;
  86182. }
  86183. }
  86184. // Create bone
  86185. var mat = configureBoneTransformation(node);
  86186. if (!parentBone && nodesToRoot.length > 0) {
  86187. parentBone = getNodeToRoot(nodesToRoot, id);
  86188. if (parentBone) {
  86189. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  86190. nodesToRootToAdd.push(parentBone);
  86191. }
  86192. }
  86193. }
  86194. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  86195. bone.id = id;
  86196. }
  86197. // Polish
  86198. var bones = newSkeleton.bones;
  86199. newSkeleton.bones = [];
  86200. for (var i = 0; i < skins.jointNames.length; i++) {
  86201. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  86202. if (!jointNode) {
  86203. continue;
  86204. }
  86205. for (var j = 0; j < bones.length; j++) {
  86206. if (bones[j].id === jointNode.id) {
  86207. newSkeleton.bones.push(bones[j]);
  86208. break;
  86209. }
  86210. }
  86211. }
  86212. newSkeleton.prepare();
  86213. // Finish
  86214. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  86215. newSkeleton.bones.push(nodesToRootToAdd[i]);
  86216. }
  86217. return newSkeleton;
  86218. };
  86219. /**
  86220. * Imports a mesh and its geometries
  86221. */
  86222. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  86223. if (!newMesh) {
  86224. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86225. newMesh.id = id;
  86226. }
  86227. if (!node.babylonNode) {
  86228. return newMesh;
  86229. }
  86230. var subMaterials = [];
  86231. var vertexData = new BABYLON.VertexData();
  86232. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  86233. var verticesStarts = new Array();
  86234. var verticesCounts = new Array();
  86235. var indexStarts = new Array();
  86236. var indexCounts = new Array();
  86237. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86238. var meshID = meshes[meshIndex];
  86239. var mesh = gltfRuntime.meshes[meshID];
  86240. if (!mesh) {
  86241. continue;
  86242. }
  86243. // Positions, normals and UVs
  86244. for (var i = 0; i < mesh.primitives.length; i++) {
  86245. // Temporary vertex data
  86246. var tempVertexData = new BABYLON.VertexData();
  86247. var primitive = mesh.primitives[i];
  86248. if (primitive.mode !== 4) {
  86249. // continue;
  86250. }
  86251. var attributes = primitive.attributes;
  86252. var accessor = null;
  86253. var buffer = null;
  86254. // Set positions, normal and uvs
  86255. for (var semantic in attributes) {
  86256. // Link accessor and buffer view
  86257. accessor = gltfRuntime.accessors[attributes[semantic]];
  86258. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86259. if (semantic === "NORMAL") {
  86260. tempVertexData.normals = new Float32Array(buffer.length);
  86261. tempVertexData.normals.set(buffer);
  86262. }
  86263. else if (semantic === "POSITION") {
  86264. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  86265. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  86266. for (var j = 0; j < buffer.length; j += 4) {
  86267. tempVertexData.positions[j] = buffer[j];
  86268. tempVertexData.positions[j + 1] = buffer[j + 1];
  86269. tempVertexData.positions[j + 2] = buffer[j + 2];
  86270. }
  86271. }
  86272. else {
  86273. tempVertexData.positions = new Float32Array(buffer.length);
  86274. tempVertexData.positions.set(buffer);
  86275. }
  86276. verticesCounts.push(tempVertexData.positions.length);
  86277. }
  86278. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  86279. var channel = Number(semantic.split("_")[1]);
  86280. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  86281. var uvs = new Float32Array(buffer.length);
  86282. uvs.set(buffer);
  86283. normalizeUVs(uvs);
  86284. tempVertexData.set(uvs, uvKind);
  86285. }
  86286. else if (semantic === "JOINT") {
  86287. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  86288. tempVertexData.matricesIndices.set(buffer);
  86289. }
  86290. else if (semantic === "WEIGHT") {
  86291. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  86292. tempVertexData.matricesWeights.set(buffer);
  86293. }
  86294. else if (semantic === "COLOR") {
  86295. tempVertexData.colors = new Float32Array(buffer.length);
  86296. tempVertexData.colors.set(buffer);
  86297. }
  86298. }
  86299. // Indices
  86300. accessor = gltfRuntime.accessors[primitive.indices];
  86301. if (accessor) {
  86302. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  86303. tempVertexData.indices = new Int32Array(buffer.length);
  86304. tempVertexData.indices.set(buffer);
  86305. indexCounts.push(tempVertexData.indices.length);
  86306. }
  86307. else {
  86308. // Set indices on the fly
  86309. var indices = [];
  86310. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  86311. indices.push(j);
  86312. }
  86313. tempVertexData.indices = new Int32Array(indices);
  86314. indexCounts.push(tempVertexData.indices.length);
  86315. }
  86316. vertexData.merge(tempVertexData);
  86317. // Sub material
  86318. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  86319. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  86320. // Update vertices start and index start
  86321. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  86322. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  86323. }
  86324. }
  86325. var material;
  86326. if (subMaterials.length > 1) {
  86327. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  86328. material.subMaterials = subMaterials;
  86329. }
  86330. else {
  86331. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  86332. }
  86333. if (subMaterials.length === 1) {
  86334. material = subMaterials[0];
  86335. }
  86336. if (!newMesh.material) {
  86337. newMesh.material = material;
  86338. }
  86339. // Apply geometry
  86340. geometry.setAllVerticesData(vertexData, false);
  86341. newMesh.computeWorldMatrix(true);
  86342. // Apply submeshes
  86343. newMesh.subMeshes = [];
  86344. var index = 0;
  86345. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  86346. var meshID = meshes[meshIndex];
  86347. var mesh = gltfRuntime.meshes[meshID];
  86348. if (!mesh) {
  86349. continue;
  86350. }
  86351. for (var i = 0; i < mesh.primitives.length; i++) {
  86352. if (mesh.primitives[i].mode !== 4) {
  86353. //continue;
  86354. }
  86355. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  86356. index++;
  86357. }
  86358. }
  86359. // Finish
  86360. return newMesh;
  86361. };
  86362. /**
  86363. * Configure node transformation from position, rotation and scaling
  86364. */
  86365. var configureNode = function (newNode, position, rotation, scaling) {
  86366. if (newNode.position) {
  86367. newNode.position = position;
  86368. }
  86369. if (newNode.rotationQuaternion || newNode.rotation) {
  86370. newNode.rotationQuaternion = rotation;
  86371. }
  86372. if (newNode.scaling) {
  86373. newNode.scaling = scaling;
  86374. }
  86375. };
  86376. /**
  86377. * Configures node from transformation matrix
  86378. */
  86379. var configureNodeFromMatrix = function (newNode, node, parent) {
  86380. if (node.matrix) {
  86381. var position = new BABYLON.Vector3(0, 0, 0);
  86382. var rotation = new BABYLON.Quaternion();
  86383. var scaling = new BABYLON.Vector3(0, 0, 0);
  86384. var mat = BABYLON.Matrix.FromArray(node.matrix);
  86385. mat.decompose(scaling, rotation, position);
  86386. configureNode(newNode, position, rotation, scaling);
  86387. }
  86388. else if (node.translation && node.rotation && node.scale) {
  86389. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  86390. }
  86391. newNode.computeWorldMatrix(true);
  86392. };
  86393. /**
  86394. * Imports a node
  86395. */
  86396. var importNode = function (gltfRuntime, node, id, parent) {
  86397. var lastNode = null;
  86398. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  86399. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  86400. return null;
  86401. }
  86402. }
  86403. // Meshes
  86404. if (node.skin) {
  86405. if (node.meshes) {
  86406. var skin = gltfRuntime.skins[node.skin];
  86407. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  86408. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  86409. if (newMesh.skeleton === null) {
  86410. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  86411. if (!skin.babylonSkeleton) {
  86412. skin.babylonSkeleton = newMesh.skeleton;
  86413. }
  86414. }
  86415. lastNode = newMesh;
  86416. }
  86417. }
  86418. else if (node.meshes) {
  86419. /**
  86420. * Improve meshes property
  86421. */
  86422. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  86423. lastNode = newMesh;
  86424. }
  86425. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86426. var light = gltfRuntime.lights[node.light];
  86427. if (light) {
  86428. if (light.type === "ambient") {
  86429. var ambienLight = light[light.type];
  86430. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86431. hemiLight.name = node.name || "";
  86432. if (ambienLight.color) {
  86433. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  86434. }
  86435. lastNode = hemiLight;
  86436. }
  86437. else if (light.type === "directional") {
  86438. var directionalLight = light[light.type];
  86439. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86440. dirLight.name = node.name || "";
  86441. if (directionalLight.color) {
  86442. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  86443. }
  86444. lastNode = dirLight;
  86445. }
  86446. else if (light.type === "point") {
  86447. var pointLight = light[light.type];
  86448. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86449. ptLight.name = node.name || "";
  86450. if (pointLight.color) {
  86451. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  86452. }
  86453. lastNode = ptLight;
  86454. }
  86455. else if (light.type === "spot") {
  86456. var spotLight = light[light.type];
  86457. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  86458. spLight.name = node.name || "";
  86459. if (spotLight.color) {
  86460. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  86461. }
  86462. if (spotLight.fallOfAngle) {
  86463. spLight.angle = spotLight.fallOfAngle;
  86464. }
  86465. if (spotLight.fallOffExponent) {
  86466. spLight.exponent = spotLight.fallOffExponent;
  86467. }
  86468. lastNode = spLight;
  86469. }
  86470. }
  86471. }
  86472. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  86473. var camera = gltfRuntime.cameras[node.camera];
  86474. if (camera) {
  86475. if (camera.type === "orthographic") {
  86476. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86477. orthoCamera.name = node.name || "";
  86478. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  86479. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86480. lastNode = orthoCamera;
  86481. }
  86482. else if (camera.type === "perspective") {
  86483. var perspectiveCamera = camera[camera.type];
  86484. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  86485. persCamera.name = node.name || "";
  86486. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  86487. if (!perspectiveCamera.aspectRatio) {
  86488. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  86489. }
  86490. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  86491. persCamera.maxZ = perspectiveCamera.zfar;
  86492. persCamera.minZ = perspectiveCamera.znear;
  86493. }
  86494. lastNode = persCamera;
  86495. }
  86496. }
  86497. }
  86498. // Empty node
  86499. if (!node.jointName) {
  86500. if (node.babylonNode) {
  86501. return node.babylonNode;
  86502. }
  86503. else if (lastNode === null) {
  86504. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  86505. node.babylonNode = dummy;
  86506. lastNode = dummy;
  86507. }
  86508. }
  86509. if (lastNode !== null) {
  86510. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  86511. configureNodeFromMatrix(lastNode, node, parent);
  86512. }
  86513. else {
  86514. var translation = node.translation || [0, 0, 0];
  86515. var rotation = node.rotation || [0, 0, 0, 1];
  86516. var scale = node.scale || [1, 1, 1];
  86517. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  86518. }
  86519. lastNode.updateCache(true);
  86520. node.babylonNode = lastNode;
  86521. }
  86522. return lastNode;
  86523. };
  86524. /**
  86525. * Traverses nodes and creates them
  86526. */
  86527. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  86528. if (meshIncluded === void 0) { meshIncluded = false; }
  86529. var node = gltfRuntime.nodes[id];
  86530. var newNode = null;
  86531. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  86532. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  86533. meshIncluded = true;
  86534. }
  86535. else {
  86536. meshIncluded = false;
  86537. }
  86538. }
  86539. else {
  86540. meshIncluded = true;
  86541. }
  86542. if (!node.jointName && meshIncluded) {
  86543. newNode = importNode(gltfRuntime, node, id, parent);
  86544. if (newNode !== null) {
  86545. newNode.id = id;
  86546. newNode.parent = parent;
  86547. }
  86548. }
  86549. if (node.children) {
  86550. for (var i = 0; i < node.children.length; i++) {
  86551. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  86552. }
  86553. }
  86554. };
  86555. /**
  86556. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  86557. */
  86558. var postLoad = function (gltfRuntime) {
  86559. // Nodes
  86560. var currentScene = gltfRuntime.currentScene;
  86561. if (currentScene) {
  86562. for (var i = 0; i < currentScene.nodes.length; i++) {
  86563. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86564. }
  86565. }
  86566. else {
  86567. for (var thing in gltfRuntime.scenes) {
  86568. currentScene = gltfRuntime.scenes[thing];
  86569. for (var i = 0; i < currentScene.nodes.length; i++) {
  86570. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  86571. }
  86572. }
  86573. }
  86574. // Set animations
  86575. loadAnimations(gltfRuntime);
  86576. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  86577. var skeleton = gltfRuntime.scene.skeletons[i];
  86578. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  86579. }
  86580. };
  86581. /**
  86582. * onBind shaderrs callback to set uniforms and matrices
  86583. */
  86584. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  86585. var materialValues = material.values || technique.parameters;
  86586. for (var unif in unTreatedUniforms) {
  86587. var uniform = unTreatedUniforms[unif];
  86588. var type = uniform.type;
  86589. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  86590. if (uniform.semantic && !uniform.source && !uniform.node) {
  86591. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  86592. }
  86593. else if (uniform.semantic && (uniform.source || uniform.node)) {
  86594. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  86595. if (source === null) {
  86596. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  86597. }
  86598. if (source === null) {
  86599. continue;
  86600. }
  86601. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  86602. }
  86603. }
  86604. else {
  86605. var value = materialValues[technique.uniforms[unif]];
  86606. if (!value) {
  86607. continue;
  86608. }
  86609. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  86610. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  86611. if (texture === null || texture === undefined) {
  86612. continue;
  86613. }
  86614. shaderMaterial.getEffect().setTexture(unif, texture);
  86615. }
  86616. else {
  86617. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  86618. }
  86619. }
  86620. }
  86621. onSuccess(shaderMaterial);
  86622. };
  86623. /**
  86624. * Prepare uniforms to send the only one time
  86625. * Loads the appropriate textures
  86626. */
  86627. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  86628. var materialValues = material.values || technique.parameters;
  86629. var techniqueUniforms = technique.uniforms;
  86630. /**
  86631. * Prepare values here (not matrices)
  86632. */
  86633. for (var unif in unTreatedUniforms) {
  86634. var uniform = unTreatedUniforms[unif];
  86635. var type = uniform.type;
  86636. var value = materialValues[techniqueUniforms[unif]];
  86637. if (value === undefined) {
  86638. // In case the value is the same for all materials
  86639. value = uniform.value;
  86640. }
  86641. if (!value) {
  86642. continue;
  86643. }
  86644. var onLoadTexture = function (uniformName) {
  86645. return function (texture) {
  86646. if (uniform.value && uniformName) {
  86647. // Static uniform
  86648. shaderMaterial.setTexture(uniformName, texture);
  86649. delete unTreatedUniforms[uniformName];
  86650. }
  86651. };
  86652. };
  86653. // Texture (sampler2D)
  86654. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  86655. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  86656. }
  86657. else {
  86658. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  86659. // Static uniform
  86660. delete unTreatedUniforms[unif];
  86661. }
  86662. }
  86663. }
  86664. };
  86665. /**
  86666. * Shader compilation failed
  86667. */
  86668. var onShaderCompileError = function (program, shaderMaterial, onError) {
  86669. return function (effect, error) {
  86670. shaderMaterial.dispose(true);
  86671. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  86672. };
  86673. };
  86674. /**
  86675. * Shader compilation success
  86676. */
  86677. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  86678. return function (_) {
  86679. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  86680. shaderMaterial.onBind = function (mesh) {
  86681. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  86682. };
  86683. };
  86684. };
  86685. /**
  86686. * Returns the appropriate uniform if already handled by babylon
  86687. */
  86688. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  86689. for (var unif in technique.uniforms) {
  86690. var uniform = technique.uniforms[unif];
  86691. var uniformParameter = technique.parameters[uniform];
  86692. if (tokenizer.currentIdentifier === unif) {
  86693. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  86694. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  86695. if (transformIndex !== -1) {
  86696. delete unTreatedUniforms[unif];
  86697. return babylonTransforms[transformIndex];
  86698. }
  86699. }
  86700. }
  86701. }
  86702. return tokenizer.currentIdentifier;
  86703. };
  86704. /**
  86705. * All shaders loaded. Create materials one by one
  86706. */
  86707. var importMaterials = function (gltfRuntime) {
  86708. // Create materials
  86709. for (var mat in gltfRuntime.materials) {
  86710. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  86711. }
  86712. };
  86713. /**
  86714. * Implementation of the base glTF spec
  86715. */
  86716. var GLTFLoaderBase = /** @class */ (function () {
  86717. function GLTFLoaderBase() {
  86718. }
  86719. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  86720. var gltfRuntime = {
  86721. extensions: {},
  86722. accessors: {},
  86723. buffers: {},
  86724. bufferViews: {},
  86725. meshes: {},
  86726. lights: {},
  86727. cameras: {},
  86728. nodes: {},
  86729. images: {},
  86730. textures: {},
  86731. shaders: {},
  86732. programs: {},
  86733. samplers: {},
  86734. techniques: {},
  86735. materials: {},
  86736. animations: {},
  86737. skins: {},
  86738. extensionsUsed: [],
  86739. scenes: {},
  86740. buffersCount: 0,
  86741. shaderscount: 0,
  86742. scene: scene,
  86743. rootUrl: rootUrl,
  86744. loadedBufferCount: 0,
  86745. loadedBufferViews: {},
  86746. loadedShaderCount: 0,
  86747. importOnlyMeshes: false,
  86748. dummyNodes: []
  86749. };
  86750. // Parse
  86751. if (parsedData.extensions) {
  86752. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  86753. }
  86754. if (parsedData.extensionsUsed) {
  86755. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  86756. }
  86757. if (parsedData.buffers) {
  86758. parseBuffers(parsedData.buffers, gltfRuntime);
  86759. }
  86760. if (parsedData.bufferViews) {
  86761. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  86762. }
  86763. if (parsedData.accessors) {
  86764. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  86765. }
  86766. if (parsedData.meshes) {
  86767. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  86768. }
  86769. if (parsedData.lights) {
  86770. parseObject(parsedData.lights, "lights", gltfRuntime);
  86771. }
  86772. if (parsedData.cameras) {
  86773. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  86774. }
  86775. if (parsedData.nodes) {
  86776. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  86777. }
  86778. if (parsedData.images) {
  86779. parseObject(parsedData.images, "images", gltfRuntime);
  86780. }
  86781. if (parsedData.textures) {
  86782. parseObject(parsedData.textures, "textures", gltfRuntime);
  86783. }
  86784. if (parsedData.shaders) {
  86785. parseShaders(parsedData.shaders, gltfRuntime);
  86786. }
  86787. if (parsedData.programs) {
  86788. parseObject(parsedData.programs, "programs", gltfRuntime);
  86789. }
  86790. if (parsedData.samplers) {
  86791. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  86792. }
  86793. if (parsedData.techniques) {
  86794. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  86795. }
  86796. if (parsedData.materials) {
  86797. parseObject(parsedData.materials, "materials", gltfRuntime);
  86798. }
  86799. if (parsedData.animations) {
  86800. parseObject(parsedData.animations, "animations", gltfRuntime);
  86801. }
  86802. if (parsedData.skins) {
  86803. parseObject(parsedData.skins, "skins", gltfRuntime);
  86804. }
  86805. if (parsedData.scenes) {
  86806. gltfRuntime.scenes = parsedData.scenes;
  86807. }
  86808. if (parsedData.scene && parsedData.scenes) {
  86809. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  86810. }
  86811. return gltfRuntime;
  86812. };
  86813. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  86814. var buffer = gltfRuntime.buffers[id];
  86815. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  86816. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  86817. }
  86818. else {
  86819. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  86820. if (request) {
  86821. onError(request.status + " " + request.statusText);
  86822. }
  86823. });
  86824. }
  86825. };
  86826. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86827. var texture = gltfRuntime.textures[id];
  86828. if (!texture || !texture.source) {
  86829. onError("");
  86830. return;
  86831. }
  86832. if (texture.babylonTexture) {
  86833. onSuccess(null);
  86834. return;
  86835. }
  86836. var source = gltfRuntime.images[texture.source];
  86837. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  86838. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  86839. }
  86840. else {
  86841. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  86842. if (request) {
  86843. onError(request.status + " " + request.statusText);
  86844. }
  86845. });
  86846. }
  86847. };
  86848. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  86849. var texture = gltfRuntime.textures[id];
  86850. if (texture.babylonTexture) {
  86851. onSuccess(texture.babylonTexture);
  86852. return;
  86853. }
  86854. var sampler = gltfRuntime.samplers[texture.sampler];
  86855. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  86856. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  86857. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  86858. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  86859. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  86860. var blob = new Blob([buffer]);
  86861. var blobURL = URL.createObjectURL(blob);
  86862. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  86863. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  86864. if (sampler.wrapS !== undefined) {
  86865. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  86866. }
  86867. if (sampler.wrapT !== undefined) {
  86868. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  86869. }
  86870. newTexture.name = id;
  86871. texture.babylonTexture = newTexture;
  86872. onSuccess(newTexture);
  86873. };
  86874. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86875. var shader = gltfRuntime.shaders[id];
  86876. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  86877. var shaderString = atob(shader.uri.split(",")[1]);
  86878. onSuccess(shaderString);
  86879. }
  86880. else {
  86881. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  86882. if (request) {
  86883. onError(request.status + " " + request.statusText);
  86884. }
  86885. });
  86886. }
  86887. };
  86888. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86889. var material = gltfRuntime.materials[id];
  86890. if (!material.technique) {
  86891. if (onError) {
  86892. onError("No technique found.");
  86893. }
  86894. return;
  86895. }
  86896. var technique = gltfRuntime.techniques[material.technique];
  86897. if (!technique) {
  86898. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  86899. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  86900. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86901. onSuccess(defaultMaterial);
  86902. return;
  86903. }
  86904. var program = gltfRuntime.programs[technique.program];
  86905. var states = technique.states;
  86906. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  86907. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  86908. var newVertexShader = "";
  86909. var newPixelShader = "";
  86910. var vertexTokenizer = new Tokenizer(vertexShader);
  86911. var pixelTokenizer = new Tokenizer(pixelShader);
  86912. var unTreatedUniforms = {};
  86913. var uniforms = [];
  86914. var attributes = [];
  86915. var samplers = [];
  86916. // Fill uniform, sampler2D and attributes
  86917. for (var unif in technique.uniforms) {
  86918. var uniform = technique.uniforms[unif];
  86919. var uniformParameter = technique.parameters[uniform];
  86920. unTreatedUniforms[unif] = uniformParameter;
  86921. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  86922. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  86923. if (transformIndex !== -1) {
  86924. uniforms.push(babylonTransforms[transformIndex]);
  86925. delete unTreatedUniforms[unif];
  86926. }
  86927. else {
  86928. uniforms.push(unif);
  86929. }
  86930. }
  86931. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  86932. samplers.push(unif);
  86933. }
  86934. else {
  86935. uniforms.push(unif);
  86936. }
  86937. }
  86938. for (var attr in technique.attributes) {
  86939. var attribute = technique.attributes[attr];
  86940. var attributeParameter = technique.parameters[attribute];
  86941. if (attributeParameter.semantic) {
  86942. attributes.push(getAttribute(attributeParameter));
  86943. }
  86944. }
  86945. // Configure vertex shader
  86946. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  86947. var tokenType = vertexTokenizer.currentToken;
  86948. if (tokenType !== ETokenType.IDENTIFIER) {
  86949. newVertexShader += vertexTokenizer.currentString;
  86950. continue;
  86951. }
  86952. var foundAttribute = false;
  86953. for (var attr in technique.attributes) {
  86954. var attribute = technique.attributes[attr];
  86955. var attributeParameter = technique.parameters[attribute];
  86956. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  86957. newVertexShader += getAttribute(attributeParameter);
  86958. foundAttribute = true;
  86959. break;
  86960. }
  86961. }
  86962. if (foundAttribute) {
  86963. continue;
  86964. }
  86965. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  86966. }
  86967. // Configure pixel shader
  86968. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  86969. var tokenType = pixelTokenizer.currentToken;
  86970. if (tokenType !== ETokenType.IDENTIFIER) {
  86971. newPixelShader += pixelTokenizer.currentString;
  86972. continue;
  86973. }
  86974. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  86975. }
  86976. // Create shader material
  86977. var shaderPath = {
  86978. vertex: program.vertexShader + id,
  86979. fragment: program.fragmentShader + id
  86980. };
  86981. var options = {
  86982. attributes: attributes,
  86983. uniforms: uniforms,
  86984. samplers: samplers,
  86985. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  86986. };
  86987. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  86988. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  86989. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  86990. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  86991. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  86992. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86993. if (states && states.functions) {
  86994. var functions = states.functions;
  86995. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  86996. shaderMaterial.backFaceCulling = false;
  86997. }
  86998. var blendFunc = functions.blendFuncSeparate;
  86999. if (blendFunc) {
  87000. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87001. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  87002. }
  87003. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87004. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87005. }
  87006. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87007. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  87008. }
  87009. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87010. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  87011. }
  87012. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87013. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  87014. }
  87015. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  87016. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  87017. }
  87018. }
  87019. }
  87020. };
  87021. return GLTFLoaderBase;
  87022. }());
  87023. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  87024. /**
  87025. * glTF V1 Loader
  87026. */
  87027. var GLTFLoader = /** @class */ (function () {
  87028. function GLTFLoader() {
  87029. // #region Stubs for IGLTFLoader interface
  87030. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  87031. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  87032. this.compileMaterials = false;
  87033. this.useClipPlane = false;
  87034. this.compileShadowGenerators = false;
  87035. this.onDisposeObservable = new BABYLON.Observable();
  87036. this.onMeshLoadedObservable = new BABYLON.Observable();
  87037. this.onTextureLoadedObservable = new BABYLON.Observable();
  87038. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87039. this.onCompleteObservable = new BABYLON.Observable();
  87040. }
  87041. GLTFLoader.RegisterExtension = function (extension) {
  87042. if (GLTFLoader.Extensions[extension.name]) {
  87043. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  87044. return;
  87045. }
  87046. GLTFLoader.Extensions[extension.name] = extension;
  87047. };
  87048. GLTFLoader.prototype.dispose = function () { };
  87049. // #endregion
  87050. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87051. var _this = this;
  87052. scene.useRightHandedSystem = true;
  87053. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87054. gltfRuntime.importOnlyMeshes = true;
  87055. if (meshesNames === "") {
  87056. gltfRuntime.importMeshesNames = [];
  87057. }
  87058. else if (typeof meshesNames === "string") {
  87059. gltfRuntime.importMeshesNames = [meshesNames];
  87060. }
  87061. else if (meshesNames && !(meshesNames instanceof Array)) {
  87062. gltfRuntime.importMeshesNames = [meshesNames];
  87063. }
  87064. else {
  87065. gltfRuntime.importMeshesNames = [];
  87066. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  87067. }
  87068. // Create nodes
  87069. _this._createNodes(gltfRuntime);
  87070. var meshes = new Array();
  87071. var skeletons = new Array();
  87072. // Fill arrays of meshes and skeletons
  87073. for (var nde in gltfRuntime.nodes) {
  87074. var node = gltfRuntime.nodes[nde];
  87075. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  87076. meshes.push(node.babylonNode);
  87077. }
  87078. }
  87079. for (var skl in gltfRuntime.skins) {
  87080. var skin = gltfRuntime.skins[skl];
  87081. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  87082. skeletons.push(skin.babylonSkeleton);
  87083. }
  87084. }
  87085. // Load buffers, shaders, materials, etc.
  87086. _this._loadBuffersAsync(gltfRuntime, function () {
  87087. _this._loadShadersAsync(gltfRuntime, function () {
  87088. importMaterials(gltfRuntime);
  87089. postLoad(gltfRuntime);
  87090. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87091. onSuccess(meshes, [], skeletons);
  87092. }
  87093. });
  87094. }, onProgress);
  87095. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  87096. onSuccess(meshes, [], skeletons);
  87097. }
  87098. }, onError);
  87099. return true;
  87100. };
  87101. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87102. var _this = this;
  87103. scene.useRightHandedSystem = true;
  87104. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  87105. // Load runtime extensios
  87106. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  87107. // Create nodes
  87108. _this._createNodes(gltfRuntime);
  87109. // Load buffers, shaders, materials, etc.
  87110. _this._loadBuffersAsync(gltfRuntime, function () {
  87111. _this._loadShadersAsync(gltfRuntime, function () {
  87112. importMaterials(gltfRuntime);
  87113. postLoad(gltfRuntime);
  87114. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  87115. onSuccess();
  87116. }
  87117. });
  87118. });
  87119. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  87120. onSuccess();
  87121. }
  87122. }, onError);
  87123. }, onError);
  87124. };
  87125. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  87126. var hasShaders = false;
  87127. var processShader = function (sha, shader) {
  87128. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  87129. gltfRuntime.loadedShaderCount++;
  87130. if (shaderString) {
  87131. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  87132. }
  87133. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  87134. onload();
  87135. }
  87136. }, function () {
  87137. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  87138. });
  87139. };
  87140. for (var sha in gltfRuntime.shaders) {
  87141. hasShaders = true;
  87142. var shader = gltfRuntime.shaders[sha];
  87143. if (shader) {
  87144. processShader.bind(this, sha, shader)();
  87145. }
  87146. else {
  87147. BABYLON.Tools.Error("No shader named: " + sha);
  87148. }
  87149. }
  87150. if (!hasShaders) {
  87151. onload();
  87152. }
  87153. };
  87154. ;
  87155. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  87156. var hasBuffers = false;
  87157. var processBuffer = function (buf, buffer) {
  87158. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  87159. gltfRuntime.loadedBufferCount++;
  87160. if (bufferView) {
  87161. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  87162. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  87163. }
  87164. gltfRuntime.loadedBufferViews[buf] = bufferView;
  87165. }
  87166. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  87167. onLoad();
  87168. }
  87169. }, function () {
  87170. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  87171. });
  87172. };
  87173. for (var buf in gltfRuntime.buffers) {
  87174. hasBuffers = true;
  87175. var buffer = gltfRuntime.buffers[buf];
  87176. if (buffer) {
  87177. processBuffer.bind(this, buf, buffer)();
  87178. }
  87179. else {
  87180. BABYLON.Tools.Error("No buffer named: " + buf);
  87181. }
  87182. }
  87183. if (!hasBuffers) {
  87184. onLoad();
  87185. }
  87186. };
  87187. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  87188. var currentScene = gltfRuntime.currentScene;
  87189. if (currentScene) {
  87190. // Only one scene even if multiple scenes are defined
  87191. for (var i = 0; i < currentScene.nodes.length; i++) {
  87192. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87193. }
  87194. }
  87195. else {
  87196. // Load all scenes
  87197. for (var thing in gltfRuntime.scenes) {
  87198. currentScene = gltfRuntime.scenes[thing];
  87199. for (var i = 0; i < currentScene.nodes.length; i++) {
  87200. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  87201. }
  87202. }
  87203. }
  87204. };
  87205. GLTFLoader.Extensions = {};
  87206. return GLTFLoader;
  87207. }());
  87208. GLTF1.GLTFLoader = GLTFLoader;
  87209. ;
  87210. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  87211. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87212. })(BABYLON || (BABYLON = {}));
  87213. //# sourceMappingURL=babylon.glTFLoader.js.map
  87214. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87215. var BABYLON;
  87216. (function (BABYLON) {
  87217. var GLTF1;
  87218. (function (GLTF1) {
  87219. /**
  87220. * Utils functions for GLTF
  87221. */
  87222. var GLTFUtils = /** @class */ (function () {
  87223. function GLTFUtils() {
  87224. }
  87225. /**
  87226. * Sets the given "parameter" matrix
  87227. * @param scene: the {BABYLON.Scene} object
  87228. * @param source: the source node where to pick the matrix
  87229. * @param parameter: the GLTF technique parameter
  87230. * @param uniformName: the name of the shader's uniform
  87231. * @param shaderMaterial: the shader material
  87232. */
  87233. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  87234. var mat = null;
  87235. if (parameter.semantic === "MODEL") {
  87236. mat = source.getWorldMatrix();
  87237. }
  87238. else if (parameter.semantic === "PROJECTION") {
  87239. mat = scene.getProjectionMatrix();
  87240. }
  87241. else if (parameter.semantic === "VIEW") {
  87242. mat = scene.getViewMatrix();
  87243. }
  87244. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  87245. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  87246. }
  87247. else if (parameter.semantic === "MODELVIEW") {
  87248. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  87249. }
  87250. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  87251. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  87252. }
  87253. else if (parameter.semantic === "MODELINVERSE") {
  87254. mat = source.getWorldMatrix().invert();
  87255. }
  87256. else if (parameter.semantic === "VIEWINVERSE") {
  87257. mat = scene.getViewMatrix().invert();
  87258. }
  87259. else if (parameter.semantic === "PROJECTIONINVERSE") {
  87260. mat = scene.getProjectionMatrix().invert();
  87261. }
  87262. else if (parameter.semantic === "MODELVIEWINVERSE") {
  87263. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  87264. }
  87265. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  87266. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  87267. }
  87268. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  87269. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  87270. }
  87271. else {
  87272. debugger;
  87273. }
  87274. if (mat) {
  87275. switch (parameter.type) {
  87276. case GLTF1.EParameterType.FLOAT_MAT2:
  87277. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  87278. break;
  87279. case GLTF1.EParameterType.FLOAT_MAT3:
  87280. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  87281. break;
  87282. case GLTF1.EParameterType.FLOAT_MAT4:
  87283. shaderMaterial.setMatrix(uniformName, mat);
  87284. break;
  87285. default: break;
  87286. }
  87287. }
  87288. };
  87289. /**
  87290. * Sets the given "parameter" matrix
  87291. * @param shaderMaterial: the shader material
  87292. * @param uniform: the name of the shader's uniform
  87293. * @param value: the value of the uniform
  87294. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  87295. */
  87296. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  87297. switch (type) {
  87298. case GLTF1.EParameterType.FLOAT:
  87299. shaderMaterial.setFloat(uniform, value);
  87300. return true;
  87301. case GLTF1.EParameterType.FLOAT_VEC2:
  87302. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  87303. return true;
  87304. case GLTF1.EParameterType.FLOAT_VEC3:
  87305. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  87306. return true;
  87307. case GLTF1.EParameterType.FLOAT_VEC4:
  87308. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  87309. return true;
  87310. default: return false;
  87311. }
  87312. };
  87313. /**
  87314. * If the uri is a base64 string
  87315. * @param uri: the uri to test
  87316. */
  87317. GLTFUtils.IsBase64 = function (uri) {
  87318. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  87319. };
  87320. /**
  87321. * Decode the base64 uri
  87322. * @param uri: the uri to decode
  87323. */
  87324. GLTFUtils.DecodeBase64 = function (uri) {
  87325. var decodedString = atob(uri.split(",")[1]);
  87326. var bufferLength = decodedString.length;
  87327. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  87328. for (var i = 0; i < bufferLength; i++) {
  87329. bufferView[i] = decodedString.charCodeAt(i);
  87330. }
  87331. return bufferView.buffer;
  87332. };
  87333. /**
  87334. * Returns the wrap mode of the texture
  87335. * @param mode: the mode value
  87336. */
  87337. GLTFUtils.GetWrapMode = function (mode) {
  87338. switch (mode) {
  87339. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  87340. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  87341. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87342. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87343. }
  87344. };
  87345. /**
  87346. * Returns the byte stride giving an accessor
  87347. * @param accessor: the GLTF accessor objet
  87348. */
  87349. GLTFUtils.GetByteStrideFromType = function (accessor) {
  87350. // Needs this function since "byteStride" isn't requiered in glTF format
  87351. var type = accessor.type;
  87352. switch (type) {
  87353. case "VEC2": return 2;
  87354. case "VEC3": return 3;
  87355. case "VEC4": return 4;
  87356. case "MAT2": return 4;
  87357. case "MAT3": return 9;
  87358. case "MAT4": return 16;
  87359. default: return 1;
  87360. }
  87361. };
  87362. /**
  87363. * Returns the texture filter mode giving a mode value
  87364. * @param mode: the filter mode value
  87365. */
  87366. GLTFUtils.GetTextureFilterMode = function (mode) {
  87367. switch (mode) {
  87368. case GLTF1.ETextureFilterType.LINEAR:
  87369. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  87370. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87371. case GLTF1.ETextureFilterType.NEAREST:
  87372. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  87373. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  87374. }
  87375. };
  87376. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  87377. var byteOffset = bufferView.byteOffset + byteOffset;
  87378. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  87379. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  87380. throw new Error("Buffer access is out of range");
  87381. }
  87382. var buffer = loadedBufferView.buffer;
  87383. byteOffset += loadedBufferView.byteOffset;
  87384. switch (componentType) {
  87385. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  87386. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  87387. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  87388. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  87389. default: return new Float32Array(buffer, byteOffset, byteLength);
  87390. }
  87391. };
  87392. /**
  87393. * Returns a buffer from its accessor
  87394. * @param gltfRuntime: the GLTF runtime
  87395. * @param accessor: the GLTF accessor
  87396. */
  87397. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  87398. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  87399. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  87400. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  87401. };
  87402. /**
  87403. * Decodes a buffer view into a string
  87404. * @param view: the buffer view
  87405. */
  87406. GLTFUtils.DecodeBufferToText = function (view) {
  87407. var result = "";
  87408. var length = view.byteLength;
  87409. for (var i = 0; i < length; ++i) {
  87410. result += String.fromCharCode(view[i]);
  87411. }
  87412. return result;
  87413. };
  87414. /**
  87415. * Returns the default material of gltf. Related to
  87416. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  87417. * @param scene: the Babylon.js scene
  87418. */
  87419. GLTFUtils.GetDefaultMaterial = function (scene) {
  87420. if (!GLTFUtils._DefaultMaterial) {
  87421. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  87422. "precision highp float;",
  87423. "",
  87424. "uniform mat4 worldView;",
  87425. "uniform mat4 projection;",
  87426. "",
  87427. "attribute vec3 position;",
  87428. "",
  87429. "void main(void)",
  87430. "{",
  87431. " gl_Position = projection * worldView * vec4(position, 1.0);",
  87432. "}"
  87433. ].join("\n");
  87434. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  87435. "precision highp float;",
  87436. "",
  87437. "uniform vec4 u_emission;",
  87438. "",
  87439. "void main(void)",
  87440. "{",
  87441. " gl_FragColor = u_emission;",
  87442. "}"
  87443. ].join("\n");
  87444. var shaderPath = {
  87445. vertex: "GLTFDefaultMaterial",
  87446. fragment: "GLTFDefaultMaterial"
  87447. };
  87448. var options = {
  87449. attributes: ["position"],
  87450. uniforms: ["worldView", "projection", "u_emission"],
  87451. samplers: new Array(),
  87452. needAlphaBlending: false
  87453. };
  87454. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  87455. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  87456. }
  87457. return GLTFUtils._DefaultMaterial;
  87458. };
  87459. // The GLTF default material
  87460. GLTFUtils._DefaultMaterial = null;
  87461. return GLTFUtils;
  87462. }());
  87463. GLTF1.GLTFUtils = GLTFUtils;
  87464. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87465. })(BABYLON || (BABYLON = {}));
  87466. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  87467. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87468. var BABYLON;
  87469. (function (BABYLON) {
  87470. var GLTF1;
  87471. (function (GLTF1) {
  87472. var GLTFLoaderExtension = /** @class */ (function () {
  87473. function GLTFLoaderExtension(name) {
  87474. this._name = name;
  87475. }
  87476. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  87477. get: function () {
  87478. return this._name;
  87479. },
  87480. enumerable: true,
  87481. configurable: true
  87482. });
  87483. /**
  87484. * Defines an override for loading the runtime
  87485. * Return true to stop further extensions from loading the runtime
  87486. */
  87487. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87488. return false;
  87489. };
  87490. /**
  87491. * Defines an onverride for creating gltf runtime
  87492. * Return true to stop further extensions from creating the runtime
  87493. */
  87494. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87495. return false;
  87496. };
  87497. /**
  87498. * Defines an override for loading buffers
  87499. * Return true to stop further extensions from loading this buffer
  87500. */
  87501. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87502. return false;
  87503. };
  87504. /**
  87505. * Defines an override for loading texture buffers
  87506. * Return true to stop further extensions from loading this texture data
  87507. */
  87508. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87509. return false;
  87510. };
  87511. /**
  87512. * Defines an override for creating textures
  87513. * Return true to stop further extensions from loading this texture
  87514. */
  87515. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87516. return false;
  87517. };
  87518. /**
  87519. * Defines an override for loading shader strings
  87520. * Return true to stop further extensions from loading this shader data
  87521. */
  87522. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87523. return false;
  87524. };
  87525. /**
  87526. * Defines an override for loading materials
  87527. * Return true to stop further extensions from loading this material
  87528. */
  87529. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87530. return false;
  87531. };
  87532. // ---------
  87533. // Utilities
  87534. // ---------
  87535. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87536. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87537. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  87538. }, function () {
  87539. setTimeout(function () {
  87540. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  87541. });
  87542. });
  87543. };
  87544. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87545. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87546. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  87547. }, function () {
  87548. setTimeout(function () {
  87549. onSuccess();
  87550. });
  87551. });
  87552. };
  87553. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  87554. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87555. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87556. }, function () {
  87557. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  87558. });
  87559. };
  87560. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  87561. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  87562. };
  87563. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87564. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87565. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  87566. }, function () {
  87567. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  87568. });
  87569. };
  87570. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87571. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87572. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  87573. }, function () {
  87574. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  87575. });
  87576. };
  87577. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87578. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87579. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  87580. }, function () {
  87581. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  87582. });
  87583. };
  87584. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  87585. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  87586. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  87587. }, function () {
  87588. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  87589. });
  87590. };
  87591. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  87592. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  87593. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  87594. if (func(loaderExtension)) {
  87595. return;
  87596. }
  87597. }
  87598. defaultFunc();
  87599. };
  87600. return GLTFLoaderExtension;
  87601. }());
  87602. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  87603. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87604. })(BABYLON || (BABYLON = {}));
  87605. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  87606. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87607. var BABYLON;
  87608. (function (BABYLON) {
  87609. var GLTF1;
  87610. (function (GLTF1) {
  87611. var BinaryExtensionBufferName = "binary_glTF";
  87612. ;
  87613. ;
  87614. var GLTFBinaryExtension = /** @class */ (function (_super) {
  87615. __extends(GLTFBinaryExtension, _super);
  87616. function GLTFBinaryExtension() {
  87617. return _super.call(this, "KHR_binary_glTF") || this;
  87618. }
  87619. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  87620. var extensionsUsed = data.json.extensionsUsed;
  87621. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  87622. return false;
  87623. }
  87624. this._bin = data.bin;
  87625. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  87626. return true;
  87627. };
  87628. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87629. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  87630. return false;
  87631. }
  87632. if (id !== BinaryExtensionBufferName) {
  87633. return false;
  87634. }
  87635. onSuccess(this._bin);
  87636. return true;
  87637. };
  87638. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  87639. var texture = gltfRuntime.textures[id];
  87640. var source = gltfRuntime.images[texture.source];
  87641. if (!source.extensions || !(this.name in source.extensions)) {
  87642. return false;
  87643. }
  87644. var sourceExt = source.extensions[this.name];
  87645. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  87646. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  87647. onSuccess(buffer);
  87648. return true;
  87649. };
  87650. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  87651. var shader = gltfRuntime.shaders[id];
  87652. if (!shader.extensions || !(this.name in shader.extensions)) {
  87653. return false;
  87654. }
  87655. var binaryExtensionShader = shader.extensions[this.name];
  87656. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  87657. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  87658. setTimeout(function () {
  87659. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  87660. onSuccess(shaderString);
  87661. });
  87662. return true;
  87663. };
  87664. return GLTFBinaryExtension;
  87665. }(GLTF1.GLTFLoaderExtension));
  87666. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  87667. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  87668. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87669. })(BABYLON || (BABYLON = {}));
  87670. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  87671. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87672. var BABYLON;
  87673. (function (BABYLON) {
  87674. var GLTF1;
  87675. (function (GLTF1) {
  87676. ;
  87677. ;
  87678. ;
  87679. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  87680. __extends(GLTFMaterialsCommonExtension, _super);
  87681. function GLTFMaterialsCommonExtension() {
  87682. return _super.call(this, "KHR_materials_common") || this;
  87683. }
  87684. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  87685. if (!gltfRuntime.extensions)
  87686. return false;
  87687. var extension = gltfRuntime.extensions[this.name];
  87688. if (!extension)
  87689. return false;
  87690. // Create lights
  87691. var lights = extension.lights;
  87692. if (lights) {
  87693. for (var thing in lights) {
  87694. var light = lights[thing];
  87695. switch (light.type) {
  87696. case "ambient":
  87697. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  87698. var ambient = light.ambient;
  87699. if (ambient) {
  87700. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  87701. }
  87702. break;
  87703. case "point":
  87704. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  87705. var point = light.point;
  87706. if (point) {
  87707. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  87708. }
  87709. break;
  87710. case "directional":
  87711. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  87712. var directional = light.directional;
  87713. if (directional) {
  87714. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  87715. }
  87716. break;
  87717. case "spot":
  87718. var spot = light.spot;
  87719. if (spot) {
  87720. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  87721. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  87722. }
  87723. break;
  87724. default:
  87725. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  87726. break;
  87727. }
  87728. }
  87729. }
  87730. return false;
  87731. };
  87732. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  87733. var material = gltfRuntime.materials[id];
  87734. if (!material || !material.extensions)
  87735. return false;
  87736. var extension = material.extensions[this.name];
  87737. if (!extension)
  87738. return false;
  87739. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  87740. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  87741. if (extension.technique === "CONSTANT") {
  87742. standardMaterial.disableLighting = true;
  87743. }
  87744. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  87745. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  87746. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  87747. // Ambient
  87748. if (typeof extension.values.ambient === "string") {
  87749. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  87750. }
  87751. else {
  87752. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  87753. }
  87754. // Diffuse
  87755. if (typeof extension.values.diffuse === "string") {
  87756. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  87757. }
  87758. else {
  87759. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  87760. }
  87761. // Emission
  87762. if (typeof extension.values.emission === "string") {
  87763. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  87764. }
  87765. else {
  87766. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  87767. }
  87768. // Specular
  87769. if (typeof extension.values.specular === "string") {
  87770. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  87771. }
  87772. else {
  87773. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  87774. }
  87775. return true;
  87776. };
  87777. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  87778. // Create buffer from texture url
  87779. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  87780. // Create texture from buffer
  87781. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  87782. }, onError);
  87783. };
  87784. return GLTFMaterialsCommonExtension;
  87785. }(GLTF1.GLTFLoaderExtension));
  87786. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  87787. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  87788. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  87789. })(BABYLON || (BABYLON = {}));
  87790. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  87791. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87792. var BABYLON;
  87793. (function (BABYLON) {
  87794. var GLTF2;
  87795. (function (GLTF2) {
  87796. /**
  87797. * Enums
  87798. */
  87799. var EComponentType;
  87800. (function (EComponentType) {
  87801. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  87802. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  87803. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  87804. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  87805. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  87806. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  87807. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  87808. var EMeshPrimitiveMode;
  87809. (function (EMeshPrimitiveMode) {
  87810. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  87811. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  87812. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  87813. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  87814. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  87815. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  87816. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  87817. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  87818. var ETextureMagFilter;
  87819. (function (ETextureMagFilter) {
  87820. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  87821. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  87822. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  87823. var ETextureMinFilter;
  87824. (function (ETextureMinFilter) {
  87825. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  87826. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  87827. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  87828. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  87829. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  87830. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  87831. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  87832. var ETextureWrapMode;
  87833. (function (ETextureWrapMode) {
  87834. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  87835. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  87836. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  87837. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  87838. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  87839. })(BABYLON || (BABYLON = {}));
  87840. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  87841. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87842. var BABYLON;
  87843. (function (BABYLON) {
  87844. var GLTF2;
  87845. (function (GLTF2) {
  87846. var GLTFLoaderTracker = /** @class */ (function () {
  87847. function GLTFLoaderTracker(onComplete) {
  87848. this._pendingCount = 0;
  87849. this._callback = onComplete;
  87850. }
  87851. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  87852. this._pendingCount++;
  87853. };
  87854. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  87855. if (--this._pendingCount === 0) {
  87856. this._callback();
  87857. }
  87858. };
  87859. return GLTFLoaderTracker;
  87860. }());
  87861. var GLTFLoader = /** @class */ (function () {
  87862. function GLTFLoader() {
  87863. this._disposed = false;
  87864. this._defaultSampler = {};
  87865. this._renderReady = false;
  87866. this._requests = new Array();
  87867. this._renderReadyObservable = new BABYLON.Observable();
  87868. // Count of pending work that needs to complete before the asset is rendered.
  87869. this._renderPendingCount = 0;
  87870. // Count of pending work that needs to complete before the loader is disposed.
  87871. this._loaderPendingCount = 0;
  87872. this._loaderTrackers = new Array();
  87873. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  87874. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  87875. this.compileMaterials = false;
  87876. this.useClipPlane = false;
  87877. this.compileShadowGenerators = false;
  87878. this.onDisposeObservable = new BABYLON.Observable();
  87879. this.onMeshLoadedObservable = new BABYLON.Observable();
  87880. this.onTextureLoadedObservable = new BABYLON.Observable();
  87881. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87882. this.onCompleteObservable = new BABYLON.Observable();
  87883. }
  87884. GLTFLoader.RegisterExtension = function (extension) {
  87885. if (GLTFLoader.Extensions[extension.name]) {
  87886. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  87887. return;
  87888. }
  87889. GLTFLoader.Extensions[extension.name] = extension;
  87890. // Keep the order of registration so that extensions registered first are called first.
  87891. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  87892. };
  87893. GLTFLoader.prototype.dispose = function () {
  87894. if (this._disposed) {
  87895. return;
  87896. }
  87897. this._disposed = true;
  87898. this._abortRequests();
  87899. this._releaseResources();
  87900. this.onDisposeObservable.notifyObservers(this);
  87901. };
  87902. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87903. var _this = this;
  87904. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  87905. if (onSuccess) {
  87906. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  87907. }
  87908. }, onProgress, onError);
  87909. };
  87910. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  87911. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  87912. };
  87913. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  87914. var _this = this;
  87915. this._babylonScene = scene;
  87916. this._rootUrl = rootUrl;
  87917. this._successCallback = onSuccess;
  87918. this._progressCallback = onProgress;
  87919. this._errorCallback = onError;
  87920. this._tryCatchOnError(function () {
  87921. _this._loadData(data);
  87922. _this._addPendingData(_this);
  87923. _this._loadDefaultScene(nodeNames);
  87924. _this._loadAnimations();
  87925. _this._removePendingData(_this);
  87926. });
  87927. };
  87928. GLTFLoader.prototype._onProgress = function () {
  87929. if (!this._progressCallback) {
  87930. return;
  87931. }
  87932. var lengthComputable = true;
  87933. var loaded = 0;
  87934. var total = 0;
  87935. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  87936. var request = _a[_i];
  87937. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  87938. return;
  87939. }
  87940. lengthComputable = lengthComputable && request._lengthComputable;
  87941. loaded += request._loaded;
  87942. total += request._total;
  87943. }
  87944. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  87945. };
  87946. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  87947. if (this._renderReady) {
  87948. func();
  87949. }
  87950. else {
  87951. this._renderReadyObservable.add(func);
  87952. }
  87953. };
  87954. GLTFLoader.prototype._onRenderReady = function () {
  87955. this._rootNode.babylonMesh.setEnabled(true);
  87956. this._startAnimations();
  87957. if (this._successCallback) {
  87958. this._successCallback();
  87959. }
  87960. this._renderReadyObservable.notifyObservers(this);
  87961. };
  87962. GLTFLoader.prototype._onComplete = function () {
  87963. this._abortRequests();
  87964. this._releaseResources();
  87965. this.onCompleteObservable.notifyObservers(this);
  87966. };
  87967. GLTFLoader.prototype._loadData = function (data) {
  87968. this._gltf = data.json;
  87969. // Assign the index of each object for convinience.
  87970. GLTFLoader._AssignIndices(this._gltf.accessors);
  87971. GLTFLoader._AssignIndices(this._gltf.animations);
  87972. GLTFLoader._AssignIndices(this._gltf.buffers);
  87973. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  87974. GLTFLoader._AssignIndices(this._gltf.images);
  87975. GLTFLoader._AssignIndices(this._gltf.materials);
  87976. GLTFLoader._AssignIndices(this._gltf.meshes);
  87977. GLTFLoader._AssignIndices(this._gltf.nodes);
  87978. GLTFLoader._AssignIndices(this._gltf.samplers);
  87979. GLTFLoader._AssignIndices(this._gltf.scenes);
  87980. GLTFLoader._AssignIndices(this._gltf.skins);
  87981. GLTFLoader._AssignIndices(this._gltf.textures);
  87982. // Handle global extensions as they may add their own data types.
  87983. GLTF2.GLTFLoaderExtension.LoadRoot(this, "#/", this._gltf);
  87984. if (data.bin) {
  87985. var buffers = this._gltf.buffers;
  87986. if (buffers && buffers[0] && !buffers[0].uri) {
  87987. var binaryBuffer = buffers[0];
  87988. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  87989. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  87990. }
  87991. binaryBuffer.loadedData = data.bin;
  87992. }
  87993. else {
  87994. BABYLON.Tools.Warn("Unexpected BIN chunk");
  87995. }
  87996. }
  87997. };
  87998. GLTFLoader.prototype._getMeshes = function () {
  87999. var meshes = new Array();
  88000. // Root mesh is always first.
  88001. meshes.push(this._rootNode.babylonMesh);
  88002. var nodes = this._gltf.nodes;
  88003. if (nodes) {
  88004. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  88005. var node = nodes_1[_i];
  88006. if (node.babylonMesh) {
  88007. meshes.push(node.babylonMesh);
  88008. }
  88009. }
  88010. }
  88011. return meshes;
  88012. };
  88013. GLTFLoader.prototype._getSkeletons = function () {
  88014. var skeletons = new Array();
  88015. var skins = this._gltf.skins;
  88016. if (skins) {
  88017. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  88018. var skin = skins_1[_i];
  88019. if (skin.babylonSkeleton) {
  88020. skeletons.push(skin.babylonSkeleton);
  88021. }
  88022. }
  88023. }
  88024. return skeletons;
  88025. };
  88026. GLTFLoader.prototype._startAnimations = function () {
  88027. var animations = this._gltf.animations;
  88028. if (!animations) {
  88029. return;
  88030. }
  88031. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  88032. var animation = animations_1[_i];
  88033. animation.babylonAnimationGroup.normalize();
  88034. }
  88035. switch (this.animationStartMode) {
  88036. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  88037. // do nothing
  88038. break;
  88039. }
  88040. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  88041. var animation = animations[0];
  88042. animation.babylonAnimationGroup.start(true);
  88043. break;
  88044. }
  88045. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  88046. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  88047. var animation = animations_2[_a];
  88048. animation.babylonAnimationGroup.start(true);
  88049. }
  88050. break;
  88051. }
  88052. default: {
  88053. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  88054. return;
  88055. }
  88056. }
  88057. };
  88058. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  88059. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  88060. if (!scene) {
  88061. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  88062. }
  88063. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  88064. };
  88065. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  88066. var _this = this;
  88067. GLTF2.GLTFLoaderExtension.LoadScene(this, context, scene);
  88068. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  88069. switch (this.coordinateSystemMode) {
  88070. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  88071. if (!this._babylonScene.useRightHandedSystem) {
  88072. this._rootNode.rotation = [0, 1, 0, 0];
  88073. this._rootNode.scale = [1, 1, -1];
  88074. this._loadTransform(this._rootNode);
  88075. }
  88076. break;
  88077. }
  88078. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  88079. this._babylonScene.useRightHandedSystem = true;
  88080. break;
  88081. }
  88082. default: {
  88083. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  88084. return;
  88085. }
  88086. }
  88087. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  88088. var nodeIndices = scene.nodes;
  88089. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  88090. node.parent = parentNode;
  88091. return true;
  88092. }, this._rootNode);
  88093. if (nodeNames) {
  88094. if (!(nodeNames instanceof Array)) {
  88095. nodeNames = [nodeNames];
  88096. }
  88097. var filteredNodeIndices_1 = new Array();
  88098. this._traverseNodes(context, nodeIndices, function (node) {
  88099. if (nodeNames.indexOf(node.name) !== -1) {
  88100. filteredNodeIndices_1.push(node.index);
  88101. node.parent = _this._rootNode;
  88102. return false;
  88103. }
  88104. return true;
  88105. }, this._rootNode);
  88106. nodeIndices = filteredNodeIndices_1;
  88107. }
  88108. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  88109. var index = nodeIndices_1[_i];
  88110. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88111. if (!node) {
  88112. throw new Error(context + ": Failed to find node " + index);
  88113. }
  88114. this._loadNode("#/nodes/" + index, node);
  88115. }
  88116. // Disable the root mesh until the asset is ready to render.
  88117. this._rootNode.babylonMesh.setEnabled(false);
  88118. };
  88119. GLTFLoader.prototype._loadNode = function (context, node) {
  88120. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  88121. return;
  88122. }
  88123. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  88124. this._loadTransform(node);
  88125. if (node.mesh != null) {
  88126. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  88127. if (!mesh) {
  88128. throw new Error(context + ": Failed to find mesh " + node.mesh);
  88129. }
  88130. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  88131. }
  88132. node.babylonMesh.parent = node.parent.babylonMesh;
  88133. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  88134. node.babylonAnimationTargets.push(node.babylonMesh);
  88135. if (node.skin != null) {
  88136. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  88137. if (!skin_1) {
  88138. throw new Error(context + ": Failed to find skin " + node.skin);
  88139. }
  88140. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  88141. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  88142. node.babylonMesh._refreshBoundingInfo(true);
  88143. });
  88144. node.babylonMesh.parent = this._rootNode.babylonMesh;
  88145. node.babylonMesh.position = BABYLON.Vector3.Zero();
  88146. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88147. node.babylonMesh.scaling = BABYLON.Vector3.One();
  88148. }
  88149. if (node.camera != null) {
  88150. // TODO: handle cameras
  88151. }
  88152. if (node.children) {
  88153. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  88154. var index = _a[_i];
  88155. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88156. if (!childNode) {
  88157. throw new Error(context + ": Failed to find child node " + index);
  88158. }
  88159. this._loadNode("#/nodes/" + index, childNode);
  88160. }
  88161. }
  88162. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  88163. };
  88164. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  88165. var _this = this;
  88166. var primitives = mesh.primitives;
  88167. if (!primitives || primitives.length === 0) {
  88168. throw new Error(context + ": Primitives are missing");
  88169. }
  88170. this._createMorphTargets(context, node, mesh);
  88171. this._loadAllVertexDataAsync(context, mesh, function () {
  88172. _this._loadMorphTargets(context, node, mesh);
  88173. var vertexData = new BABYLON.VertexData();
  88174. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  88175. var primitive = primitives_1[_i];
  88176. vertexData.merge(primitive.vertexData);
  88177. }
  88178. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  88179. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  88180. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  88181. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  88182. node.babylonMesh.subMeshes = [];
  88183. var verticesStart = 0;
  88184. var indicesStart = 0;
  88185. for (var index = 0; index < primitives.length; index++) {
  88186. var vertexData_1 = primitives[index].vertexData;
  88187. var verticesCount = vertexData_1.positions.length;
  88188. var indicesCount = vertexData_1.indices.length;
  88189. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  88190. verticesStart += verticesCount;
  88191. indicesStart += indicesCount;
  88192. }
  88193. ;
  88194. });
  88195. if (primitives.length === 1) {
  88196. var primitive = primitives[0];
  88197. if (primitive.material == null) {
  88198. node.babylonMesh.material = this._getDefaultMaterial();
  88199. }
  88200. else {
  88201. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  88202. if (!material) {
  88203. throw new Error(context + ": Failed to find material " + primitive.material);
  88204. }
  88205. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88206. if (isNew) {
  88207. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88208. }
  88209. node.babylonMesh.material = babylonMaterial;
  88210. });
  88211. }
  88212. }
  88213. else {
  88214. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  88215. node.babylonMesh.material = multiMaterial;
  88216. var subMaterials_1 = multiMaterial.subMaterials;
  88217. var _loop_1 = function (index) {
  88218. var primitive = primitives[index];
  88219. if (primitive.material == null) {
  88220. subMaterials_1[index] = this_1._getDefaultMaterial();
  88221. }
  88222. else {
  88223. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  88224. if (!material) {
  88225. throw new Error(context + ": Failed to find material " + primitive.material);
  88226. }
  88227. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  88228. if (isNew) {
  88229. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  88230. }
  88231. subMaterials_1[index] = babylonMaterial;
  88232. });
  88233. }
  88234. };
  88235. var this_1 = this;
  88236. for (var index = 0; index < primitives.length; index++) {
  88237. _loop_1(index);
  88238. }
  88239. ;
  88240. }
  88241. };
  88242. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  88243. var primitives = mesh.primitives;
  88244. var numRemainingPrimitives = primitives.length;
  88245. var _loop_2 = function (index) {
  88246. var primitive = primitives[index];
  88247. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  88248. primitive.vertexData = vertexData;
  88249. if (--numRemainingPrimitives === 0) {
  88250. onSuccess();
  88251. }
  88252. });
  88253. };
  88254. var this_2 = this;
  88255. for (var index = 0; index < primitives.length; index++) {
  88256. _loop_2(index);
  88257. }
  88258. };
  88259. /**
  88260. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  88261. * @param {ArrayBufferView} data
  88262. * @param {IGLTFAccessor} accessor
  88263. */
  88264. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  88265. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  88266. return data;
  88267. }
  88268. var buffer = data;
  88269. var factor = 1;
  88270. switch (accessor.componentType) {
  88271. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88272. factor = 1 / 255;
  88273. break;
  88274. }
  88275. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88276. factor = 1 / 65535;
  88277. break;
  88278. }
  88279. default: {
  88280. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88281. }
  88282. }
  88283. var result = new Float32Array(accessor.count * 2);
  88284. for (var i = 0; i < result.length; ++i) {
  88285. result[i] = buffer[i] * factor;
  88286. }
  88287. return result;
  88288. };
  88289. /**
  88290. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  88291. * @param {ArrayBufferView} data
  88292. * @param {IGLTFAccessor} accessor
  88293. */
  88294. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  88295. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  88296. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  88297. return data;
  88298. }
  88299. var buffer = data;
  88300. var factor = 1;
  88301. switch (accessor.componentType) {
  88302. case GLTF2.EComponentType.FLOAT: {
  88303. factor = 1;
  88304. break;
  88305. }
  88306. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88307. factor = 1 / 255;
  88308. break;
  88309. }
  88310. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88311. factor = 1 / 65535;
  88312. break;
  88313. }
  88314. default: {
  88315. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  88316. }
  88317. }
  88318. var result = new Float32Array(accessor.count * 4);
  88319. if (colorComponentCount === 4) {
  88320. for (var i = 0; i < result.length; ++i) {
  88321. result[i] = buffer[i] * factor;
  88322. }
  88323. }
  88324. else {
  88325. var offset = 0;
  88326. for (var i = 0; i < result.length; ++i) {
  88327. if ((i + 1) % 4 === 0) {
  88328. result[i] = 1;
  88329. }
  88330. else {
  88331. result[i] = buffer[offset++] * factor;
  88332. }
  88333. }
  88334. }
  88335. return result;
  88336. };
  88337. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  88338. var _this = this;
  88339. var attributes = primitive.attributes;
  88340. if (!attributes) {
  88341. throw new Error(context + ": Attributes are missing");
  88342. }
  88343. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  88344. // TODO: handle other primitive modes
  88345. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  88346. }
  88347. var vertexData = new BABYLON.VertexData();
  88348. var numRemainingAttributes = Object.keys(attributes).length;
  88349. var _loop_3 = function (attribute) {
  88350. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  88351. if (!accessor) {
  88352. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88353. }
  88354. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88355. switch (attribute) {
  88356. case "POSITION": {
  88357. vertexData.positions = data;
  88358. break;
  88359. }
  88360. case "NORMAL": {
  88361. vertexData.normals = data;
  88362. break;
  88363. }
  88364. case "TANGENT": {
  88365. vertexData.tangents = data;
  88366. break;
  88367. }
  88368. case "TEXCOORD_0": {
  88369. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88370. break;
  88371. }
  88372. case "TEXCOORD_1": {
  88373. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  88374. break;
  88375. }
  88376. case "JOINTS_0": {
  88377. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  88378. break;
  88379. }
  88380. case "WEIGHTS_0": {
  88381. //TODO: need to add support for normalized weights.
  88382. vertexData.matricesWeights = data;
  88383. break;
  88384. }
  88385. case "COLOR_0": {
  88386. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  88387. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  88388. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  88389. mesh.hasVertexAlpha = hasVertexAlpha;
  88390. }
  88391. break;
  88392. }
  88393. default: {
  88394. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88395. break;
  88396. }
  88397. }
  88398. if (--numRemainingAttributes === 0) {
  88399. if (primitive.indices == null) {
  88400. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  88401. for (var i = 0; i < vertexData.indices.length; i++) {
  88402. vertexData.indices[i] = i;
  88403. }
  88404. onSuccess(vertexData);
  88405. }
  88406. else {
  88407. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  88408. if (!indicesAccessor) {
  88409. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  88410. }
  88411. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  88412. vertexData.indices = data;
  88413. onSuccess(vertexData);
  88414. });
  88415. }
  88416. }
  88417. });
  88418. };
  88419. var this_3 = this;
  88420. for (var attribute in attributes) {
  88421. _loop_3(attribute);
  88422. }
  88423. };
  88424. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  88425. var primitives = mesh.primitives;
  88426. var targets = primitives[0].targets;
  88427. if (!targets) {
  88428. return;
  88429. }
  88430. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  88431. var primitive = primitives_2[_i];
  88432. if (!primitive.targets || primitive.targets.length != targets.length) {
  88433. throw new Error(context + ": All primitives are required to list the same number of targets");
  88434. }
  88435. }
  88436. var morphTargetManager = new BABYLON.MorphTargetManager();
  88437. node.babylonMesh.morphTargetManager = morphTargetManager;
  88438. for (var index = 0; index < targets.length; index++) {
  88439. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  88440. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  88441. }
  88442. };
  88443. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  88444. var morphTargetManager = node.babylonMesh.morphTargetManager;
  88445. if (!morphTargetManager) {
  88446. return;
  88447. }
  88448. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  88449. var numTargets = morphTargetManager.numTargets;
  88450. for (var index = 0; index < numTargets; index++) {
  88451. var vertexData = new BABYLON.VertexData();
  88452. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88453. var primitive = _a[_i];
  88454. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  88455. }
  88456. if (!vertexData.positions) {
  88457. throw new Error(context + ": Positions are missing");
  88458. }
  88459. var target = morphTargetManager.getTarget(index);
  88460. target.setPositions(vertexData.positions);
  88461. target.setNormals(vertexData.normals);
  88462. target.setTangents(vertexData.tangents);
  88463. }
  88464. });
  88465. };
  88466. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  88467. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  88468. var _loop_4 = function (primitive) {
  88469. var targets = primitive.targets;
  88470. primitive.targetsVertexData = new Array(targets.length);
  88471. var _loop_5 = function (index) {
  88472. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  88473. primitive.targetsVertexData[index] = vertexData;
  88474. if (--numRemainingTargets === 0) {
  88475. onSuccess();
  88476. }
  88477. });
  88478. };
  88479. for (var index = 0; index < targets.length; index++) {
  88480. _loop_5(index);
  88481. }
  88482. };
  88483. var this_4 = this;
  88484. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  88485. var primitive = _a[_i];
  88486. _loop_4(primitive);
  88487. }
  88488. };
  88489. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  88490. var targetVertexData = new BABYLON.VertexData();
  88491. var numRemainingAttributes = Object.keys(attributes).length;
  88492. var _loop_6 = function (attribute) {
  88493. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  88494. if (!accessor) {
  88495. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  88496. }
  88497. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88498. // glTF stores morph target information as deltas while babylon.js expects the final data.
  88499. // As a result we have to add the original data to the delta to calculate the final data.
  88500. var values = data;
  88501. switch (attribute) {
  88502. case "POSITION": {
  88503. for (var i = 0; i < values.length; i++) {
  88504. values[i] += vertexData.positions[i];
  88505. }
  88506. targetVertexData.positions = values;
  88507. break;
  88508. }
  88509. case "NORMAL": {
  88510. for (var i = 0; i < values.length; i++) {
  88511. values[i] += vertexData.normals[i];
  88512. }
  88513. targetVertexData.normals = values;
  88514. break;
  88515. }
  88516. case "TANGENT": {
  88517. // Tangent data for morph targets is stored as xyz delta.
  88518. // The vertexData.tangent is stored as xyzw.
  88519. // So we need to skip every fourth vertexData.tangent.
  88520. for (var i = 0, j = 0; i < values.length; i++, j++) {
  88521. values[i] += vertexData.tangents[j];
  88522. if ((i + 1) % 3 == 0) {
  88523. j++;
  88524. }
  88525. }
  88526. targetVertexData.tangents = values;
  88527. break;
  88528. }
  88529. default: {
  88530. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  88531. break;
  88532. }
  88533. }
  88534. if (--numRemainingAttributes === 0) {
  88535. onSuccess(targetVertexData);
  88536. }
  88537. });
  88538. };
  88539. var this_5 = this;
  88540. for (var attribute in attributes) {
  88541. _loop_6(attribute);
  88542. }
  88543. };
  88544. GLTFLoader.prototype._loadTransform = function (node) {
  88545. var position = BABYLON.Vector3.Zero();
  88546. var rotation = BABYLON.Quaternion.Identity();
  88547. var scaling = BABYLON.Vector3.One();
  88548. if (node.matrix) {
  88549. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  88550. matrix.decompose(scaling, rotation, position);
  88551. }
  88552. else {
  88553. if (node.translation)
  88554. position = BABYLON.Vector3.FromArray(node.translation);
  88555. if (node.rotation)
  88556. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  88557. if (node.scale)
  88558. scaling = BABYLON.Vector3.FromArray(node.scale);
  88559. }
  88560. node.babylonMesh.position = position;
  88561. node.babylonMesh.rotationQuaternion = rotation;
  88562. node.babylonMesh.scaling = scaling;
  88563. };
  88564. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  88565. var _this = this;
  88566. if (skin.babylonSkeleton) {
  88567. onSuccess();
  88568. return;
  88569. }
  88570. var skeletonId = "skeleton" + skin.index;
  88571. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  88572. if (skin.inverseBindMatrices == null) {
  88573. this._loadBones(context, skin, null);
  88574. onSuccess();
  88575. }
  88576. else {
  88577. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  88578. if (!accessor) {
  88579. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  88580. }
  88581. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  88582. _this._loadBones(context, skin, data);
  88583. onSuccess();
  88584. });
  88585. }
  88586. };
  88587. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  88588. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  88589. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  88590. node.babylonAnimationTargets.push(babylonBone);
  88591. return babylonBone;
  88592. };
  88593. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  88594. var babylonBones = {};
  88595. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  88596. var index = _a[_i];
  88597. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88598. if (!node) {
  88599. throw new Error(context + ": Failed to find joint " + index);
  88600. }
  88601. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  88602. }
  88603. };
  88604. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  88605. var babylonBone = babylonBones[node.index];
  88606. if (babylonBone) {
  88607. return babylonBone;
  88608. }
  88609. var boneIndex = skin.joints.indexOf(node.index);
  88610. var baseMatrix = BABYLON.Matrix.Identity();
  88611. if (inverseBindMatrixData && boneIndex !== -1) {
  88612. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  88613. baseMatrix.invertToRef(baseMatrix);
  88614. }
  88615. var babylonParentBone = null;
  88616. if (node.parent !== this._rootNode) {
  88617. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  88618. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  88619. }
  88620. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  88621. babylonBones[node.index] = babylonBone;
  88622. return babylonBone;
  88623. };
  88624. GLTFLoader.prototype._getNodeMatrix = function (node) {
  88625. return node.matrix ?
  88626. BABYLON.Matrix.FromArray(node.matrix) :
  88627. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  88628. };
  88629. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  88630. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  88631. var index = indices_1[_i];
  88632. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  88633. if (!node) {
  88634. throw new Error(context + ": Failed to find node " + index);
  88635. }
  88636. this._traverseNode(context, node, action, parentNode);
  88637. }
  88638. };
  88639. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  88640. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  88641. return;
  88642. }
  88643. if (!action(node, parentNode)) {
  88644. return;
  88645. }
  88646. if (node.children) {
  88647. this._traverseNodes(context, node.children, action, node);
  88648. }
  88649. };
  88650. GLTFLoader.prototype._loadAnimations = function () {
  88651. var animations = this._gltf.animations;
  88652. if (!animations) {
  88653. return;
  88654. }
  88655. for (var index = 0; index < animations.length; index++) {
  88656. var animation = animations[index];
  88657. this._loadAnimation("#/animations/" + index, animation);
  88658. }
  88659. };
  88660. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  88661. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  88662. for (var index = 0; index < animation.channels.length; index++) {
  88663. var channel = GLTFLoader._GetProperty(animation.channels, index);
  88664. if (!channel) {
  88665. throw new Error(context + ": Failed to find channel " + index);
  88666. }
  88667. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  88668. if (!sampler) {
  88669. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  88670. }
  88671. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  88672. }
  88673. };
  88674. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  88675. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  88676. if (!targetNode) {
  88677. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  88678. }
  88679. var targetPath;
  88680. var animationType;
  88681. switch (channel.target.path) {
  88682. case "translation": {
  88683. targetPath = "position";
  88684. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88685. break;
  88686. }
  88687. case "rotation": {
  88688. targetPath = "rotationQuaternion";
  88689. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  88690. break;
  88691. }
  88692. case "scale": {
  88693. targetPath = "scaling";
  88694. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88695. break;
  88696. }
  88697. case "weights": {
  88698. targetPath = "influence";
  88699. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  88700. break;
  88701. }
  88702. default: {
  88703. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  88704. }
  88705. }
  88706. var inputData;
  88707. var outputData;
  88708. var checkSuccess = function () {
  88709. if (!inputData || !outputData) {
  88710. return;
  88711. }
  88712. var outputBufferOffset = 0;
  88713. var getNextOutputValue;
  88714. switch (targetPath) {
  88715. case "position": {
  88716. getNextOutputValue = function () {
  88717. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  88718. outputBufferOffset += 3;
  88719. return value;
  88720. };
  88721. break;
  88722. }
  88723. case "rotationQuaternion": {
  88724. getNextOutputValue = function () {
  88725. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  88726. outputBufferOffset += 4;
  88727. return value;
  88728. };
  88729. break;
  88730. }
  88731. case "scaling": {
  88732. getNextOutputValue = function () {
  88733. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  88734. outputBufferOffset += 3;
  88735. return value;
  88736. };
  88737. break;
  88738. }
  88739. case "influence": {
  88740. getNextOutputValue = function () {
  88741. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  88742. var value = new Array(numTargets);
  88743. for (var i = 0; i < numTargets; i++) {
  88744. value[i] = outputData[outputBufferOffset++];
  88745. }
  88746. return value;
  88747. };
  88748. break;
  88749. }
  88750. }
  88751. sampler.interpolation = sampler.interpolation || "LINEAR";
  88752. var getNextKey;
  88753. switch (sampler.interpolation) {
  88754. case "STEP": {
  88755. getNextKey = function (frameIndex) { return ({
  88756. frame: inputData[frameIndex],
  88757. value: getNextOutputValue(),
  88758. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  88759. }); };
  88760. break;
  88761. }
  88762. case "LINEAR": {
  88763. getNextKey = function (frameIndex) { return ({
  88764. frame: inputData[frameIndex],
  88765. value: getNextOutputValue()
  88766. }); };
  88767. break;
  88768. }
  88769. case "CUBICSPLINE": {
  88770. getNextKey = function (frameIndex) { return ({
  88771. frame: inputData[frameIndex],
  88772. inTangent: getNextOutputValue(),
  88773. value: getNextOutputValue(),
  88774. outTangent: getNextOutputValue()
  88775. }); };
  88776. break;
  88777. }
  88778. default: {
  88779. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  88780. }
  88781. }
  88782. ;
  88783. var keys;
  88784. if (inputData.length === 1) {
  88785. var key = getNextKey(0);
  88786. keys = [
  88787. { frame: key.frame, value: key.value },
  88788. { frame: key.frame + 1, value: key.value }
  88789. ];
  88790. }
  88791. else {
  88792. keys = new Array(inputData.length);
  88793. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  88794. keys[frameIndex] = getNextKey(frameIndex);
  88795. }
  88796. }
  88797. if (targetPath === "influence") {
  88798. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  88799. var _loop_7 = function (targetIndex) {
  88800. var morphTarget = morphTargetManager.getTarget(targetIndex);
  88801. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  88802. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  88803. babylonAnimation.setKeys(keys.map(function (key) { return ({
  88804. frame: key.frame,
  88805. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  88806. value: key.value[targetIndex],
  88807. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  88808. }); }));
  88809. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  88810. };
  88811. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  88812. _loop_7(targetIndex);
  88813. }
  88814. }
  88815. else {
  88816. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  88817. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  88818. babylonAnimation.setKeys(keys);
  88819. if (targetNode.babylonAnimationTargets) {
  88820. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  88821. var target = _a[_i];
  88822. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  88823. }
  88824. }
  88825. }
  88826. };
  88827. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  88828. if (!inputAccessor) {
  88829. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  88830. }
  88831. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  88832. inputData = data;
  88833. checkSuccess();
  88834. });
  88835. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  88836. if (!outputAccessor) {
  88837. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  88838. }
  88839. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  88840. outputData = data;
  88841. checkSuccess();
  88842. });
  88843. };
  88844. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  88845. var _this = this;
  88846. this._addPendingData(buffer);
  88847. if (buffer.loadedData) {
  88848. onSuccess(buffer.loadedData);
  88849. this._removePendingData(buffer);
  88850. }
  88851. else if (buffer.loadedObservable) {
  88852. buffer.loadedObservable.add(function (buffer) {
  88853. onSuccess(buffer.loadedData);
  88854. _this._removePendingData(buffer);
  88855. });
  88856. }
  88857. else {
  88858. if (!buffer.uri) {
  88859. throw new Error(context + ": Uri is missing");
  88860. }
  88861. buffer.loadedObservable = new BABYLON.Observable();
  88862. buffer.loadedObservable.add(function (buffer) {
  88863. onSuccess(buffer.loadedData);
  88864. _this._removePendingData(buffer);
  88865. });
  88866. this._loadUriAsync(context, buffer.uri, function (data) {
  88867. buffer.loadedData = data;
  88868. buffer.loadedObservable.notifyObservers(buffer);
  88869. buffer.loadedObservable = undefined;
  88870. });
  88871. }
  88872. };
  88873. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  88874. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  88875. if (!buffer) {
  88876. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  88877. }
  88878. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  88879. var data;
  88880. try {
  88881. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  88882. }
  88883. catch (e) {
  88884. throw new Error(context + ": " + e.message);
  88885. }
  88886. onSuccess(data);
  88887. });
  88888. };
  88889. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  88890. var _this = this;
  88891. if (accessor.sparse) {
  88892. throw new Error(context + ": Sparse accessors are not currently supported");
  88893. }
  88894. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  88895. if (!bufferView) {
  88896. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  88897. }
  88898. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  88899. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  88900. var data;
  88901. var byteOffset = accessor.byteOffset || 0;
  88902. var byteStride = bufferView.byteStride;
  88903. if (byteStride === 0) {
  88904. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  88905. }
  88906. try {
  88907. switch (accessor.componentType) {
  88908. case GLTF2.EComponentType.BYTE: {
  88909. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88910. break;
  88911. }
  88912. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  88913. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88914. break;
  88915. }
  88916. case GLTF2.EComponentType.SHORT: {
  88917. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88918. break;
  88919. }
  88920. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  88921. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88922. break;
  88923. }
  88924. case GLTF2.EComponentType.UNSIGNED_INT: {
  88925. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88926. break;
  88927. }
  88928. case GLTF2.EComponentType.FLOAT: {
  88929. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  88930. break;
  88931. }
  88932. default: {
  88933. throw new Error(context + ": Invalid component type " + accessor.componentType);
  88934. }
  88935. }
  88936. }
  88937. catch (e) {
  88938. throw new Error(context + ": " + e);
  88939. }
  88940. onSuccess(data);
  88941. });
  88942. };
  88943. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  88944. byteOffset += data.byteOffset;
  88945. var targetLength = count * numComponents;
  88946. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  88947. return new typedArray(data.buffer, byteOffset, targetLength);
  88948. }
  88949. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  88950. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  88951. var targetBuffer = new typedArray(targetLength);
  88952. var sourceIndex = 0;
  88953. var targetIndex = 0;
  88954. while (targetIndex < targetLength) {
  88955. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  88956. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  88957. targetIndex++;
  88958. }
  88959. sourceIndex += elementStride;
  88960. }
  88961. return targetBuffer;
  88962. };
  88963. GLTFLoader.prototype._addPendingData = function (data) {
  88964. if (!this._renderReady) {
  88965. this._renderPendingCount++;
  88966. }
  88967. this._addLoaderPendingData(data);
  88968. };
  88969. GLTFLoader.prototype._removePendingData = function (data) {
  88970. var _this = this;
  88971. if (!this._renderReady) {
  88972. if (--this._renderPendingCount === 0) {
  88973. this._addLoaderPendingData(this);
  88974. this._compileMaterialsAsync(function () {
  88975. _this._compileShadowGeneratorsAsync(function () {
  88976. _this._removeLoaderPendingData(_this);
  88977. _this._renderReady = true;
  88978. _this._onRenderReady();
  88979. });
  88980. });
  88981. }
  88982. }
  88983. this._removeLoaderPendingData(data);
  88984. };
  88985. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  88986. this._loaderPendingCount++;
  88987. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  88988. var tracker = _a[_i];
  88989. tracker._addPendingData(data);
  88990. }
  88991. };
  88992. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  88993. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  88994. var tracker = _a[_i];
  88995. tracker._removePendingData(data);
  88996. }
  88997. if (--this._loaderPendingCount === 0) {
  88998. this._onComplete();
  88999. }
  89000. };
  89001. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  89002. var _this = this;
  89003. var tracker = new GLTFLoaderTracker(function () {
  89004. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  89005. onComplete();
  89006. });
  89007. this._loaderTrackers.push(tracker);
  89008. this._addLoaderPendingData(tracker);
  89009. action();
  89010. this._removeLoaderPendingData(tracker);
  89011. };
  89012. GLTFLoader.prototype._getDefaultMaterial = function () {
  89013. if (!this._defaultMaterial) {
  89014. var id = "__gltf_default";
  89015. var material = this._babylonScene.getMaterialByName(id);
  89016. if (!material) {
  89017. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  89018. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89019. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89020. material.metallic = 1;
  89021. material.roughness = 1;
  89022. }
  89023. this._defaultMaterial = material;
  89024. }
  89025. return this._defaultMaterial;
  89026. };
  89027. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  89028. var babylonMaterial = material.babylonMaterial;
  89029. // Ensure metallic workflow
  89030. babylonMaterial.metallic = 1;
  89031. babylonMaterial.roughness = 1;
  89032. var properties = material.pbrMetallicRoughness;
  89033. if (!properties) {
  89034. return;
  89035. }
  89036. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  89037. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  89038. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  89039. if (properties.baseColorTexture) {
  89040. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  89041. if (!texture) {
  89042. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  89043. }
  89044. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  89045. }
  89046. if (properties.metallicRoughnessTexture) {
  89047. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  89048. if (!texture) {
  89049. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  89050. }
  89051. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  89052. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  89053. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  89054. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  89055. }
  89056. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  89057. };
  89058. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  89059. if (material.babylonMaterial) {
  89060. assign(material.babylonMaterial, false);
  89061. return;
  89062. }
  89063. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  89064. return;
  89065. }
  89066. this._createPbrMaterial(material);
  89067. this._loadMaterialBaseProperties(context, material);
  89068. this._loadMaterialMetallicRoughnessProperties(context, material);
  89069. assign(material.babylonMaterial, true);
  89070. };
  89071. GLTFLoader.prototype._createPbrMaterial = function (material) {
  89072. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  89073. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  89074. material.babylonMaterial = babylonMaterial;
  89075. };
  89076. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  89077. var babylonMaterial = material.babylonMaterial;
  89078. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  89079. if (material.doubleSided) {
  89080. babylonMaterial.backFaceCulling = false;
  89081. babylonMaterial.twoSidedLighting = true;
  89082. }
  89083. if (material.normalTexture) {
  89084. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  89085. if (!texture) {
  89086. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  89087. }
  89088. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  89089. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  89090. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  89091. if (material.normalTexture.scale != null) {
  89092. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  89093. }
  89094. }
  89095. if (material.occlusionTexture) {
  89096. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  89097. if (!texture) {
  89098. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  89099. }
  89100. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  89101. babylonMaterial.useAmbientInGrayScale = true;
  89102. if (material.occlusionTexture.strength != null) {
  89103. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  89104. }
  89105. }
  89106. if (material.emissiveTexture) {
  89107. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  89108. if (!texture) {
  89109. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  89110. }
  89111. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  89112. }
  89113. };
  89114. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  89115. var babylonMaterial = material.babylonMaterial;
  89116. var alphaMode = material.alphaMode || "OPAQUE";
  89117. switch (alphaMode) {
  89118. case "OPAQUE": {
  89119. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  89120. break;
  89121. }
  89122. case "MASK": {
  89123. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  89124. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  89125. if (colorFactor) {
  89126. if (colorFactor[3] == 0) {
  89127. babylonMaterial.alphaCutOff = 1;
  89128. }
  89129. else {
  89130. babylonMaterial.alphaCutOff /= colorFactor[3];
  89131. }
  89132. }
  89133. if (babylonMaterial.albedoTexture) {
  89134. babylonMaterial.albedoTexture.hasAlpha = true;
  89135. }
  89136. break;
  89137. }
  89138. case "BLEND": {
  89139. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  89140. if (colorFactor) {
  89141. babylonMaterial.alpha = colorFactor[3];
  89142. }
  89143. if (babylonMaterial.albedoTexture) {
  89144. babylonMaterial.albedoTexture.hasAlpha = true;
  89145. babylonMaterial.useAlphaFromAlbedoTexture = true;
  89146. }
  89147. break;
  89148. }
  89149. default: {
  89150. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  89151. }
  89152. }
  89153. };
  89154. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  89155. var _this = this;
  89156. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  89157. if (!sampler) {
  89158. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  89159. }
  89160. this._loadSampler("#/samplers/" + sampler.index, sampler);
  89161. this._addPendingData(texture);
  89162. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  89163. _this._tryCatchOnError(function () {
  89164. _this._removePendingData(texture);
  89165. });
  89166. }, function (message) {
  89167. _this._tryCatchOnError(function () {
  89168. throw new Error(context + ": " + message);
  89169. });
  89170. });
  89171. if (texture.url) {
  89172. babylonTexture.updateURL(texture.url);
  89173. }
  89174. else if (texture.dataReadyObservable) {
  89175. texture.dataReadyObservable.add(function (texture) {
  89176. babylonTexture.updateURL(texture.url);
  89177. });
  89178. }
  89179. else {
  89180. texture.dataReadyObservable = new BABYLON.Observable();
  89181. texture.dataReadyObservable.add(function (texture) {
  89182. babylonTexture.updateURL(texture.url);
  89183. });
  89184. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  89185. if (!image_1) {
  89186. throw new Error(context + ": Failed to find source " + texture.source);
  89187. }
  89188. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  89189. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  89190. texture.dataReadyObservable.notifyObservers(texture);
  89191. texture.dataReadyObservable = undefined;
  89192. });
  89193. }
  89194. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  89195. babylonTexture.wrapU = sampler.wrapU;
  89196. babylonTexture.wrapV = sampler.wrapV;
  89197. babylonTexture.name = texture.name || "texture" + texture.index;
  89198. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  89199. return babylonTexture;
  89200. };
  89201. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  89202. if (sampler.noMipMaps != undefined) {
  89203. return;
  89204. }
  89205. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  89206. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  89207. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  89208. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  89209. };
  89210. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  89211. if (image.uri) {
  89212. this._loadUriAsync(context, image.uri, onSuccess);
  89213. }
  89214. else {
  89215. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  89216. if (!bufferView) {
  89217. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  89218. }
  89219. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  89220. }
  89221. };
  89222. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  89223. var _this = this;
  89224. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  89225. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  89226. return;
  89227. }
  89228. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  89229. throw new Error(context + ": Uri '" + uri + "' is invalid");
  89230. }
  89231. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  89232. _this._tryCatchOnError(function () {
  89233. onSuccess(new Uint8Array(data));
  89234. });
  89235. }, function (event) {
  89236. _this._tryCatchOnError(function () {
  89237. if (request && !_this._renderReady) {
  89238. request._lengthComputable = event.lengthComputable;
  89239. request._loaded = event.loaded;
  89240. request._total = event.total;
  89241. _this._onProgress();
  89242. }
  89243. });
  89244. }, this._babylonScene.database, true, function (request, exception) {
  89245. _this._tryCatchOnError(function () {
  89246. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  89247. });
  89248. });
  89249. this._requests.push(request);
  89250. };
  89251. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  89252. if (this._disposed) {
  89253. return;
  89254. }
  89255. try {
  89256. handler();
  89257. }
  89258. catch (e) {
  89259. BABYLON.Tools.Error("glTF Loader: " + e.message);
  89260. if (this._errorCallback) {
  89261. this._errorCallback(e.message, e);
  89262. }
  89263. this.dispose();
  89264. }
  89265. };
  89266. GLTFLoader._AssignIndices = function (array) {
  89267. if (array) {
  89268. for (var index = 0; index < array.length; index++) {
  89269. array[index].index = index;
  89270. }
  89271. }
  89272. };
  89273. GLTFLoader._GetProperty = function (array, index) {
  89274. if (!array || index == undefined || !array[index]) {
  89275. return null;
  89276. }
  89277. return array[index];
  89278. };
  89279. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  89280. // Set defaults if undefined
  89281. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  89282. switch (mode) {
  89283. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  89284. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  89285. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  89286. default:
  89287. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  89288. return BABYLON.Texture.WRAP_ADDRESSMODE;
  89289. }
  89290. };
  89291. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  89292. // Set defaults if undefined
  89293. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  89294. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  89295. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  89296. switch (minFilter) {
  89297. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  89298. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  89299. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  89300. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  89301. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  89302. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89303. default:
  89304. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89305. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  89306. }
  89307. }
  89308. else {
  89309. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  89310. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  89311. }
  89312. switch (minFilter) {
  89313. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  89314. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  89315. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89316. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  89317. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  89318. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  89319. default:
  89320. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  89321. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  89322. }
  89323. }
  89324. };
  89325. GLTFLoader._GetNumComponents = function (context, type) {
  89326. switch (type) {
  89327. case "SCALAR": return 1;
  89328. case "VEC2": return 2;
  89329. case "VEC3": return 3;
  89330. case "VEC4": return 4;
  89331. case "MAT2": return 4;
  89332. case "MAT3": return 9;
  89333. case "MAT4": return 16;
  89334. }
  89335. throw new Error(context + ": Invalid type " + type);
  89336. };
  89337. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  89338. var _this = this;
  89339. if (this.useClipPlane) {
  89340. babylonMaterial.forceCompilation(babylonMesh, function () {
  89341. babylonMaterial.forceCompilation(babylonMesh, function () {
  89342. _this._tryCatchOnError(onSuccess);
  89343. }, { clipPlane: true });
  89344. });
  89345. }
  89346. else {
  89347. babylonMaterial.forceCompilation(babylonMesh, function () {
  89348. _this._tryCatchOnError(onSuccess);
  89349. });
  89350. }
  89351. };
  89352. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  89353. if (!this.compileMaterials || !this._gltf.materials) {
  89354. onSuccess();
  89355. return;
  89356. }
  89357. var meshes = this._getMeshes();
  89358. var remaining = 0;
  89359. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  89360. var mesh = meshes_1[_i];
  89361. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89362. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  89363. var subMaterial = _b[_a];
  89364. if (subMaterial) {
  89365. remaining++;
  89366. }
  89367. }
  89368. }
  89369. else if (mesh.material) {
  89370. remaining++;
  89371. }
  89372. }
  89373. if (remaining === 0) {
  89374. onSuccess();
  89375. return;
  89376. }
  89377. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  89378. var mesh = meshes_2[_c];
  89379. if (mesh.material instanceof BABYLON.MultiMaterial) {
  89380. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  89381. var subMaterial = _e[_d];
  89382. if (subMaterial) {
  89383. this._compileMaterialAsync(subMaterial, mesh, function () {
  89384. if (--remaining === 0) {
  89385. onSuccess();
  89386. }
  89387. });
  89388. }
  89389. }
  89390. }
  89391. else if (mesh.material) {
  89392. this._compileMaterialAsync(mesh.material, mesh, function () {
  89393. if (--remaining === 0) {
  89394. onSuccess();
  89395. }
  89396. });
  89397. }
  89398. }
  89399. };
  89400. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  89401. var _this = this;
  89402. if (!this.compileShadowGenerators) {
  89403. onSuccess();
  89404. return;
  89405. }
  89406. var lights = this._babylonScene.lights;
  89407. var remaining = 0;
  89408. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  89409. var light = lights_1[_i];
  89410. var generator = light.getShadowGenerator();
  89411. if (generator) {
  89412. remaining++;
  89413. }
  89414. }
  89415. if (remaining === 0) {
  89416. onSuccess();
  89417. return;
  89418. }
  89419. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  89420. var light = lights_2[_a];
  89421. var generator = light.getShadowGenerator();
  89422. if (generator) {
  89423. generator.forceCompilation(function () {
  89424. if (--remaining === 0) {
  89425. _this._tryCatchOnError(onSuccess);
  89426. }
  89427. });
  89428. }
  89429. }
  89430. };
  89431. GLTFLoader.prototype._abortRequests = function () {
  89432. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  89433. var request = _a[_i];
  89434. request.abort();
  89435. }
  89436. this._requests.length = 0;
  89437. };
  89438. GLTFLoader.prototype._releaseResources = function () {
  89439. if (this._gltf.textures) {
  89440. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  89441. var texture = _a[_i];
  89442. if (texture.url) {
  89443. URL.revokeObjectURL(texture.url);
  89444. texture.url = undefined;
  89445. }
  89446. }
  89447. }
  89448. };
  89449. GLTFLoader.Extensions = {};
  89450. return GLTFLoader;
  89451. }());
  89452. GLTF2.GLTFLoader = GLTFLoader;
  89453. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  89454. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89455. })(BABYLON || (BABYLON = {}));
  89456. //# sourceMappingURL=babylon.glTFLoader.js.map
  89457. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89458. var BABYLON;
  89459. (function (BABYLON) {
  89460. var GLTF2;
  89461. (function (GLTF2) {
  89462. /**
  89463. * Utils functions for GLTF
  89464. */
  89465. var GLTFUtils = /** @class */ (function () {
  89466. function GLTFUtils() {
  89467. }
  89468. /**
  89469. * If the uri is a base64 string
  89470. * @param uri: the uri to test
  89471. */
  89472. GLTFUtils.IsBase64 = function (uri) {
  89473. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  89474. };
  89475. /**
  89476. * Decode the base64 uri
  89477. * @param uri: the uri to decode
  89478. */
  89479. GLTFUtils.DecodeBase64 = function (uri) {
  89480. var decodedString = atob(uri.split(",")[1]);
  89481. var bufferLength = decodedString.length;
  89482. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  89483. for (var i = 0; i < bufferLength; i++) {
  89484. bufferView[i] = decodedString.charCodeAt(i);
  89485. }
  89486. return bufferView.buffer;
  89487. };
  89488. GLTFUtils.ValidateUri = function (uri) {
  89489. return (uri.indexOf("..") === -1);
  89490. };
  89491. return GLTFUtils;
  89492. }());
  89493. GLTF2.GLTFUtils = GLTFUtils;
  89494. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89495. })(BABYLON || (BABYLON = {}));
  89496. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  89497. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89498. var BABYLON;
  89499. (function (BABYLON) {
  89500. var GLTF2;
  89501. (function (GLTF2) {
  89502. var GLTFLoaderExtension = /** @class */ (function () {
  89503. function GLTFLoaderExtension() {
  89504. this.enabled = true;
  89505. }
  89506. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  89507. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  89508. GLTFLoaderExtension.prototype._loadRoot = function (loader, context, root) { return false; };
  89509. GLTFLoaderExtension.prototype._loadScene = function (loader, context, scene) { return false; };
  89510. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  89511. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  89512. var _this = this;
  89513. if (!property.extensions) {
  89514. return false;
  89515. }
  89516. var extension = property.extensions[this.name];
  89517. if (!extension) {
  89518. return false;
  89519. }
  89520. // Clear out the extension before executing the action to avoid recursing into the same property.
  89521. property.extensions[this.name] = undefined;
  89522. action(context + "extensions/" + this.name, extension, function () {
  89523. // Restore the extension after completing the action.
  89524. property.extensions[_this.name] = extension;
  89525. });
  89526. return true;
  89527. };
  89528. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  89529. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  89530. };
  89531. GLTFLoaderExtension.LoadRoot = function (loader, context, root) {
  89532. return this._ApplyExtensions(function (extension) { return extension._loadRoot(loader, context, root); });
  89533. };
  89534. GLTFLoaderExtension.LoadScene = function (loader, context, scene) {
  89535. return this._ApplyExtensions(function (extension) { return extension._loadScene(loader, context, scene); });
  89536. };
  89537. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  89538. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  89539. };
  89540. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  89541. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  89542. };
  89543. GLTFLoaderExtension._ApplyExtensions = function (action) {
  89544. var extensions = GLTFLoaderExtension._Extensions;
  89545. if (!extensions) {
  89546. return false;
  89547. }
  89548. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  89549. var extension = extensions_1[_i];
  89550. if (extension.enabled && action(extension)) {
  89551. return true;
  89552. }
  89553. }
  89554. return false;
  89555. };
  89556. //
  89557. // Utilities
  89558. //
  89559. GLTFLoaderExtension._Extensions = [];
  89560. return GLTFLoaderExtension;
  89561. }());
  89562. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  89563. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89564. })(BABYLON || (BABYLON = {}));
  89565. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  89566. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89567. var BABYLON;
  89568. (function (BABYLON) {
  89569. var GLTF2;
  89570. (function (GLTF2) {
  89571. var Extensions;
  89572. (function (Extensions) {
  89573. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  89574. var MSFTLOD = /** @class */ (function (_super) {
  89575. __extends(MSFTLOD, _super);
  89576. function MSFTLOD() {
  89577. var _this = _super !== null && _super.apply(this, arguments) || this;
  89578. /**
  89579. * Specify the minimal delay between LODs in ms (default = 250)
  89580. */
  89581. _this.Delay = 250;
  89582. return _this;
  89583. }
  89584. Object.defineProperty(MSFTLOD.prototype, "name", {
  89585. get: function () {
  89586. return "MSFT_lod";
  89587. },
  89588. enumerable: true,
  89589. configurable: true
  89590. });
  89591. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  89592. return this._loadExtension(context, node, function (context, extension, onComplete) {
  89593. for (var i = extension.ids.length - 1; i >= 0; i--) {
  89594. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  89595. if (!lodNode) {
  89596. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  89597. }
  89598. loader._traverseNode(context, lodNode, action, parentNode);
  89599. }
  89600. loader._traverseNode(context, node, action, parentNode);
  89601. onComplete();
  89602. });
  89603. };
  89604. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  89605. var _this = this;
  89606. return this._loadExtension(context, node, function (context, extension, onComplete) {
  89607. var nodes = [node];
  89608. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  89609. var index = _a[_i];
  89610. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  89611. if (!lodNode) {
  89612. throw new Error(context + ": Failed to find node " + index);
  89613. }
  89614. nodes.push(lodNode);
  89615. }
  89616. loader._addLoaderPendingData(node);
  89617. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  89618. loader._removeLoaderPendingData(node);
  89619. onComplete();
  89620. });
  89621. });
  89622. };
  89623. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  89624. var _this = this;
  89625. loader._whenAction(function () {
  89626. loader._loadNode(context, nodes[index]);
  89627. }, function () {
  89628. if (index !== nodes.length - 1) {
  89629. var previousNode = nodes[index + 1];
  89630. previousNode.babylonMesh.setEnabled(false);
  89631. }
  89632. if (index === 0) {
  89633. onComplete();
  89634. return;
  89635. }
  89636. setTimeout(function () {
  89637. loader._tryCatchOnError(function () {
  89638. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  89639. });
  89640. }, _this.Delay);
  89641. });
  89642. };
  89643. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  89644. var _this = this;
  89645. return this._loadExtension(context, material, function (context, extension, onComplete) {
  89646. var materials = [material];
  89647. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  89648. var index = _a[_i];
  89649. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  89650. if (!lodMaterial) {
  89651. throw new Error(context + ": Failed to find material " + index);
  89652. }
  89653. materials.push(lodMaterial);
  89654. }
  89655. loader._addLoaderPendingData(material);
  89656. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  89657. loader._removeLoaderPendingData(material);
  89658. onComplete();
  89659. });
  89660. });
  89661. };
  89662. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  89663. var _this = this;
  89664. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  89665. if (index === materials.length - 1) {
  89666. assign(babylonMaterial, isNew);
  89667. // Load the next LOD when the loader is ready to render.
  89668. loader._executeWhenRenderReady(function () {
  89669. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  89670. });
  89671. }
  89672. else {
  89673. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  89674. assign(babylonMaterial, isNew);
  89675. if (index === 0) {
  89676. onComplete();
  89677. }
  89678. else {
  89679. setTimeout(function () {
  89680. loader._tryCatchOnError(function () {
  89681. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  89682. });
  89683. }, _this.Delay);
  89684. }
  89685. });
  89686. }
  89687. });
  89688. };
  89689. return MSFTLOD;
  89690. }(GLTF2.GLTFLoaderExtension));
  89691. Extensions.MSFTLOD = MSFTLOD;
  89692. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  89693. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  89694. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89695. })(BABYLON || (BABYLON = {}));
  89696. //# sourceMappingURL=MSFT_lod.js.map
  89697. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89698. var BABYLON;
  89699. (function (BABYLON) {
  89700. var GLTF2;
  89701. (function (GLTF2) {
  89702. var Extensions;
  89703. (function (Extensions) {
  89704. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  89705. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  89706. function KHRMaterialsPbrSpecularGlossiness() {
  89707. return _super !== null && _super.apply(this, arguments) || this;
  89708. }
  89709. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  89710. get: function () {
  89711. return "KHR_materials_pbrSpecularGlossiness";
  89712. },
  89713. enumerable: true,
  89714. configurable: true
  89715. });
  89716. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  89717. var _this = this;
  89718. return this._loadExtension(context, material, function (context, extension, onComplete) {
  89719. loader._createPbrMaterial(material);
  89720. loader._loadMaterialBaseProperties(context, material);
  89721. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  89722. assign(material.babylonMaterial, true);
  89723. onComplete();
  89724. });
  89725. };
  89726. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  89727. var babylonMaterial = material.babylonMaterial;
  89728. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  89729. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  89730. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  89731. if (properties.diffuseTexture) {
  89732. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  89733. if (!texture) {
  89734. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  89735. }
  89736. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  89737. }
  89738. if (properties.specularGlossinessTexture) {
  89739. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  89740. if (!texture) {
  89741. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  89742. }
  89743. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  89744. babylonMaterial.reflectivityTexture.hasAlpha = true;
  89745. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  89746. }
  89747. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  89748. };
  89749. return KHRMaterialsPbrSpecularGlossiness;
  89750. }(GLTF2.GLTFLoaderExtension));
  89751. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  89752. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  89753. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  89754. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89755. })(BABYLON || (BABYLON = {}));
  89756. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  89757. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  89758. var BABYLON;
  89759. (function (BABYLON) {
  89760. var GLTF2;
  89761. (function (GLTF2) {
  89762. var Extensions;
  89763. (function (Extensions) {
  89764. var KHRLights = /** @class */ (function (_super) {
  89765. __extends(KHRLights, _super);
  89766. function KHRLights() {
  89767. return _super !== null && _super.apply(this, arguments) || this;
  89768. }
  89769. Object.defineProperty(KHRLights.prototype, "name", {
  89770. get: function () {
  89771. return "KHR_lights";
  89772. },
  89773. enumerable: true,
  89774. configurable: true
  89775. });
  89776. KHRLights.prototype.applyCommonProperties = function (light, lightInfo) {
  89777. if (lightInfo.color) {
  89778. light.diffuse.copyFromFloats(lightInfo.color[0], lightInfo.color[1], lightInfo.color[2]);
  89779. }
  89780. else {
  89781. light.diffuse.copyFromFloats(1, 1, 1);
  89782. }
  89783. if (lightInfo.intensity !== undefined) {
  89784. light.intensity = lightInfo.intensity;
  89785. }
  89786. else {
  89787. light.intensity = 1;
  89788. }
  89789. };
  89790. KHRLights.prototype._loadScene = function (loader, context, scene) {
  89791. return this._loadExtension(context, scene, function (context, extension, onComplete) {
  89792. if (extension.light >= 0 && loader._gltf.extensions) {
  89793. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  89794. if (lightInfo.type !== 'ambient') {
  89795. return;
  89796. }
  89797. var lightColor = lightInfo.color ? lightInfo.color : [1, 1, 1];
  89798. loader._babylonScene.ambientColor.copyFromFloats(lightColor[0], lightColor[1], lightColor[2]);
  89799. }
  89800. onComplete();
  89801. });
  89802. };
  89803. KHRLights.prototype._loadNode = function (loader, context, node) {
  89804. var _this = this;
  89805. return this._loadExtension(context, node, function (context, extension, onComplete) {
  89806. if (extension.light >= 0 && loader._gltf.extensions) {
  89807. var lightInfo = loader._gltf.extensions.KHR_lights.lights[extension.light];
  89808. var name_1 = node.name || 'Light';
  89809. var matrix = void 0;
  89810. if (node.matrix) {
  89811. matrix = BABYLON.Matrix.FromArray(node.matrix);
  89812. }
  89813. else {
  89814. matrix = BABYLON.Matrix.Identity();
  89815. }
  89816. var direction = new BABYLON.Vector3(0, 0, 1);
  89817. if (lightInfo.type == 'directional' || lightInfo.type == 'spot') {
  89818. var rotationMatrix = matrix.getRotationMatrix();
  89819. BABYLON.Vector3.TransformCoordinatesToRef(direction, rotationMatrix, direction);
  89820. }
  89821. var light = void 0;
  89822. if (lightInfo.type == 'directional') {
  89823. light = new BABYLON.DirectionalLight(name_1, direction, loader._babylonScene);
  89824. }
  89825. else {
  89826. var position = matrix.getTranslation();
  89827. if (lightInfo.type == 'spot') {
  89828. var angle = lightInfo.spot && lightInfo.spot.outerConeAngle ? lightInfo.spot.outerConeAngle : Math.PI / 2;
  89829. light = new BABYLON.SpotLight(name_1, position, direction, angle, 2, loader._babylonScene);
  89830. }
  89831. else {
  89832. light = new BABYLON.PointLight(name_1, position, loader._babylonScene);
  89833. }
  89834. }
  89835. _this.applyCommonProperties(light, lightInfo);
  89836. extension.babylonLight = light;
  89837. extension.babylonLight.parent = node.parent ? node.parent.babylonMesh : null;
  89838. if (node.children) {
  89839. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  89840. var index = _a[_i];
  89841. var childNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  89842. if (!childNode) {
  89843. throw new Error(context + ": Failed to find child node " + index);
  89844. }
  89845. loader._loadNode("#/nodes/" + index, childNode);
  89846. }
  89847. }
  89848. }
  89849. onComplete();
  89850. });
  89851. };
  89852. KHRLights.prototype._loadRoot = function (loader, context, root) {
  89853. return this._loadExtension(context, root, function (context, extension, onComplete) {
  89854. extension.lights.forEach(function (light, idx) {
  89855. light.index = idx;
  89856. });
  89857. onComplete();
  89858. });
  89859. };
  89860. return KHRLights;
  89861. }(GLTF2.GLTFLoaderExtension));
  89862. Extensions.KHRLights = KHRLights;
  89863. GLTF2.GLTFLoader.RegisterExtension(new KHRLights());
  89864. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  89865. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  89866. })(BABYLON || (BABYLON = {}));
  89867. //# sourceMappingURL=KHR_lights.js.map
  89868. (function universalModuleDefinition(root, factory) {
  89869. var f = factory();
  89870. if (root && root["BABYLON"]) {
  89871. return;
  89872. }
  89873. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  89874. globalObject["BABYLON"] = f;
  89875. if(typeof exports === 'object' && typeof module === 'object')
  89876. module.exports = f;
  89877. else if(typeof define === 'function' && define.amd)
  89878. define(["BABYLON"], factory);
  89879. else if(typeof exports === 'object')
  89880. exports["BABYLON"] = f;
  89881. else {
  89882. root["BABYLON"] = f;
  89883. }
  89884. })(this, function() {
  89885. return BABYLON;
  89886. });